Skip to content
Fix Code Error

Getting duplicated cardviews using SwipeRefresh Layout

July 4, 2021 by Code Error
Posted By: Anonymous

So here is my problem, I got an API that gives me the lastest news of many sources. Each one of them goes with a cardview. The problem here is, while I’m using the swipeRefresh, it gets duplicated cardViews with the same news, like if I have 10 news, it duplicates to 20 with the same ones.
Here is my code where I apply the swipeRefresh:


package com.example.newsapp4;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import com.example.newsapp4.Model.Articles;
import com.example.newsapp4.Model.Headlines;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class bbcnews extends AppCompatActivity {
    Adapter adapter;
    Intent intencion;
    RecyclerView recyclerView;
    public static String source = "My Source";
    public static String API_KEY = "My API Key";
    SwipeRefreshLayout srl;

    List<Articles> articles = new ArrayList<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bbcnews);

        srl = findViewById(R.id.swipeRefresh);
        srl.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                retrieveJson(source, API_KEY);
            }
        });


        recyclerView = findViewById(R.id.recyclerView1);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));


        adapter = new Adapter(bbcnews.this,articles);
        recyclerView.setAdapter(adapter);
        retrieveJson(source, API_KEY);

    }

    public void retrieveJson(String source, String apiKey){

        srl.setRefreshing(true);
        Call<Headlines> call = ApiClient.getInstance().getApi().getHeadlines(source, apiKey);
        call.enqueue(new Callback<Headlines>() {
            @Override
            public void onResponse(Call<Headlines> call, Response<Headlines> response) {
                if(response.isSuccessful() && response.body().getArticles() != null){
                    srl.setRefreshing(false);
                    articles.clear();
                    articles = response.body().getArticles();
                    adapter.setArticles(articles);
                }
            }


            @Override
            public void onFailure(Call<Headlines> call, Throwable t) {
                srl.setRefreshing(false);
                Toast.makeText(bbcnews.this, t.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    public String getCountry(){
        Locale locale = Locale.getDefault();
        String country = locale.getCountry();
        return country.toLowerCase();

    }

    public void aPerfil(View vista){
        intencion = new Intent(this, profile_activity.class);
        startActivity(intencion);
    }
}

I don’t think that I need to put the xml code with the progressbar and the swipeRefresh but here are both:

This one is the Items.xml where I created the cardView:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <androidx.cardview.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        app:cardElevation="4dp"
        android:id="@+id/cardView"
        app:cardCornerRadius="10dp">

        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="200dp">

            <ProgressBar
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:id="@+id/loader"/>


            <ImageView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:id="@+id/image"
                android:scaleType="centerCrop"
                android:src="@drawable/img"/>

            <ImageView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="@drawable/gradient" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="TITLE"
                android:textSize="20dp"
                android:padding="10dp"
                android:fontFamily="@font/g_bold"
                android:textColor="@color/white"
                android:id="@+id/tvTitle"/>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="bottom"
                android:orientation="horizontal">

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Source"
                    android:textSize="16dp"
                    android:padding="10dp"
                    android:ems="15"
                    android:fontFamily="@font/g_light"
                    android:textColor="@color/white"
                    android:id="@+id/tvSource"/>
                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:fontFamily="@font/g_light"
                    android:gravity="right"
                    android:text="Date"
                    android:textColor="@color/white"
                    android:padding="10dp"
                    android:textSize="16dp"
                    android:id="@+id/tvDate"/>




            </LinearLayout>
        </FrameLayout>

    </androidx.cardview.widget.CardView>



</LinearLayout>

And here the one with the swipeRefresh in the recyclerView:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="@color/white"
    tools:context=".bbcnews">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="DINGO BBC NEWS"
        android:textColor="@color/black"
        android:textSize="20sp"
        android:fontFamily="@font/g_bold"
        android:background="@color/white"
        android:padding="10dp"
        android:textAlignment="center"/>



    <GridLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:paddingTop="10dp"
        android:paddingBottom="10dp"
        android:columnCount="2"
        android:paddingLeft="20dp"
        android:paddingRight="5dp"
        android:background="@drawable/black_background"
        android:rowCount="2">

        <EditText
            android:id="@+id/editTextTextPersonName"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:ems="10"
            android:hint="Search"
            android:textColor="@color/grey"
            android:textColorHint="@color/grey"
            android:padding="5dp"
            android:layout_column="0"
            android:background="@drawable/black_background"
            android:layout_row="0"
            android:layout_columnWeight="1"
            android:inputType="textPersonName" />

        <Button
            android:id="@+id/button2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:paddingRight="20dp"
            android:background="@drawable/black_background"
            android:drawableRight="@drawable/ic_baseline_search_24"
            android:layout_column="1"
            android:layout_row="0"/>

    </GridLayout>


    <androidx.swiperefreshlayout.widget.SwipeRefreshLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/swipeRefresh">

        <androidx.recyclerview.widget.RecyclerView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginTop="5dp"
            android:id="@+id/recyclerView1"/>

    </androidx.swiperefreshlayout.widget.SwipeRefreshLayout>


</LinearLayout>

Also this is my adapter.java code:


package com.example.newsapp4;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView;

import com.example.newsapp4.Model.Articles;
import com.squareup.picasso.Picasso;

import java.util.List;

public class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder> {

    Context context;
    List<Articles> articles;

    public Adapter(Context context, List<Articles> articles) {
        this.context = context;
        this.articles = articles;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.items, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        final Articles a = articles.get(position);

        String imageUrl = a.getUrlToImage();

        holder.tvTitle.setText(a.getTitle());
        holder.tvSource.setText(a.getSource().getName());
        holder.tvDate.setText(a.getPublishedAt());


        Picasso.with(context).load(imageUrl).into(holder.imageView);
    }

    @Override
    public int getItemCount() {
        return articles.size();
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {

        TextView tvTitle,tvSource,tvDate;
        ImageView imageView;
        CardView cardView;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);

            tvTitle = itemView.findViewById(R.id.tvTitle);
            tvSource = itemView.findViewById(R.id.tvSource);
            tvDate = itemView.findViewById(R.id.tvDate);
            imageView = itemView.findViewById(R.id.image);
            cardView = itemView.findViewById(R.id.cardView);

        }
    }

    public void setArticles(List<Articles> articles) {
        this.articles.addAll(articles);
        int count = getItemCount();
        notifyItemRangeInserted(count, count + articles.size());
    }


}

Thanks for your time!

Solution

   // Clear adapter list before add to list.

  public void setArticles(List<Articles> articles) {
        
                   if(this.articles!=null && this.articles.size()>0)
                      this.articles.clear();
        
                this.articles.addAll(articles);
                int count = getItemCount();
                notifyItemRangeInserted(count, count + articles.size());
            }
Answered By: Anonymous

Related Articles

  • Unable to run Robolectric and Espresso with a…
  • Item position in RecyclerView only changing when dragging…
  • Error in styles_base.xml file - android app - No resource…
  • MaterialCardView is in front of NavigationView. How can I…
  • How to add 'load more' functionality to items on a page with…
  • CardView cardElevation draws random square inside of…
  • Getting wrong position on RecyclerView
  • Unable to create call adapter for class java.lang.Object…
  • Button is null object reference (Android Studio)
  • Render problem in Android Studio arctic fox

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

recyclerview opens wrong item after filtering list using search

Next Post:

PHP + Laravel: Indirect modification of overloaded element of IlluminateSupportCollection has no effect

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

  • Get code errors & solutions at akashmittal.com
© 2022 Fix Code Error