RecyleView showing all items duplicates

Related searches

I am trying to display posts from a server in listView. So I used recycle-view to achieve that. Everything is working fine except that ll items are displaying twice.

I counted the total fetched items from server, and the count is 5, but adapter.getItemCount is showing 10.

After searching hours on the internet, I tried following :

public long getItemId(int position) {
    return position;
public int getItemViewType(int position) {
    return position;



Below is my fragment...

package com.example.projectName;

import static android.content.Context.MODE_PRIVATE;
import static android.webkit.ConsoleMessage.MessageLevel.LOG;
import static com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions.withCrossFade;

public class HomeFollowersFragment extends Fragment implements InfiniteScrollListener.OnLoadMoreListener, RecyclerViewItemListener {

    private static final String TAG = "HomeFollowersFragment";
    private static final String URL = "";
    private RecyclerView recyclerView;
    private ProgressBar postLoader;
    FFmpeg ffmpeg;
//    private List<Movie> movieList;
//    private HomeAdapter mAdapter;

    private List<PostList> postListGlobal = new ArrayList<>();
    List<VerticalDataModal> verticalDataModals;
    List<HorizontalDataModal> horizontalDataModals;
    private SwipeRefreshLayout swipeMore;
    private InfiniteScrollListener infiniteScrollListener;
    private HomeFragmentAdapter homeFragmentAdapter;

    SharedPreferences sharedPreferences;
    private Boolean isLoggedIn = false;
    private String email = "";
    private String token = "";
    private String userId = "";

    private Dialog customLoader;
    SkeletonScreen skeletonScreen;

    private int pastVisiblesItems, visibleItemCount, totalItemCount;
    private boolean loading = false;
    private EndlessScrollListener scrollListener;

    SharedPreferences sp;
    SharedPreferences.Editor Ed;

    public HomeFollowersFragment() {
     * @return A new instance of fragment HomeFollowersFragment.
    public static HomeFollowersFragment newInstance() {
        return new HomeFollowersFragment();

    public void onCreate(Bundle savedInstanceState) {

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_home, container, false);
//        ((AppCompatActivity) getActivity()).getSupportActionBar().show();

            sharedPreferences = getActivity().getSharedPreferences("Login", MODE_PRIVATE);
            email = sharedPreferences.getString("email", null);
            token = sharedPreferences.getString("token", null);
            isLoggedIn = sharedPreferences.getBoolean("isLoggedIn", false);
            userId = sharedPreferences.getString("id", null);
        }catch (Exception e){
            Log.d("StackError", "StackError: "+e);
        sp = getActivity().getSharedPreferences("Posts", MODE_PRIVATE);
        if(!isLoggedIn || token == null || userId == null){
            Intent intent = new Intent(getActivity(), RegisterActivity.class);
            intent.putExtra("loginFrom", "profile");

        recyclerView = view.findViewById(;
        postLoader = view.findViewById(;
        swipeMore = view.findViewById(;

        homeFragmentAdapter = new HomeFragmentAdapter(postListGlobal, this, "home");

            skeletonScreen = Skeleton.bind(recyclerView)
                    .show(); //default count is 10
        RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(getActivity(), 2);
        StaggeredGridLayoutManager sLayoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);


        customLoader = new Dialog(getActivity(),;
        View loaderView = getLayoutInflater().inflate(R.layout.custom_loading_layout, null);
        customLoader.getWindow().getAttributes().windowAnimations =;

        ImageView imageLoader = loaderView.findViewById(;

        if(homeFragmentAdapter.getItemCount() == 0 && !loading){
            // server fetchdata
            Log.d(TAG, "no item available..");
            loading = true;
        swipeMore.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            public void onRefresh() {
                Log.d(TAG, "on refresh...");
        return view;
    public void onItemClicked(int position) {
        Log.d(TAG, "click position: "+position);
//        Toast.makeText(getActivity(),""+position, Toast.LENGTH_SHORT).show();

    public int getLastVisibleItem(int[] lastVisibleItemPositions) {
        int maxSize = 0;
        for (int i = 0; i < lastVisibleItemPositions.length; i++) {
            if (i == 0) {
                maxSize = lastVisibleItemPositions[i];
            else if (lastVisibleItemPositions[i] > maxSize) {
                maxSize = lastVisibleItemPositions[i];
        return maxSize;
    public void onLoadMore() {
        new Handler().postDelayed(new Runnable() {
            public void run() {
                Toast.makeText(getContext(), "load more here...", Toast.LENGTH_LONG).show();
//                fetchStoreItems();
        }, 2000);
    private void fetchStoreItems() {
        RequestQueue queue = Volley.newRequestQueue(getActivity());
        Log.d(TAG, "Post Data Followers: "+Constant.FETCH_POSTS_API);
        CacheRequest cacheRequest = new CacheRequest(0, Constant.FETCH_POSTS_API, new Response.Listener<NetworkResponse>() {
            public void onResponse(NetworkResponse response) {
                try {
                    final String jsonString = new String(,
                    if (response == null) {
                        Toast.makeText(getActivity(), "Couldn't fetch the store items! Pleas try again.", Toast.LENGTH_LONG).show();
                        loading = false;
                    JSONObject postObj = new JSONObject(jsonString);
                    System.out.println("post full data... : " + postObj);
                    if (postObj.getBoolean("Status")) {
                        try {
                            JSONArray arrayResponse = postObj.optJSONArray("Data");
                            int dataArrLength = arrayResponse.length();
                            if(dataArrLength == 0){
                                Toast.makeText(getActivity(), "No posts available at this time, you can create yout own post by clicking on mic button", Toast.LENGTH_SHORT).show();
                            Log.d(TAG, "Total Posts count: "+dataArrLength);
                            for(int i=0; i<dataArrLength; i++) {
                                try {
                                    JSONObject dataListObj = arrayResponse.optJSONObject(i);
                                    System.out.println("post full data... : " + dataListObj);

                                    JSONObject postDetailObj = dataListObj.optJSONObject("post_detail");
                                    JSONObject followDtatusObj = dataListObj.optJSONObject("follow_status");
                                    JSONArray postFilesArr = dataListObj.optJSONArray("post_files");
                                    JSONObject userDatasObj = postDetailObj.optJSONObject("user");

                                    String userId = userDatasObj.optString("id");
                                    String userName = userDatasObj.optString("email");
                                    String userImage = userDatasObj.optString("email");

                                    boolean followStatus = followDtatusObj.optBoolean("follow");

                                    String postId = postDetailObj.optString("id");
                                    String postTitle = postDetailObj.optString("post_title");
                                    String postDescription = postDetailObj.optString("post_description");
                                    String postCoverUrl = postDetailObj.optString("post_coverurl", "1");
                                    String postViewType = postDetailObj.optString("view_type", "1");
                                    String postAllowComment = postDetailObj.optString("allow_comments", "1");
                                    String postAllowDownload = postDetailObj.optString("allow_download", "1");
                                    String postTotalPost = postDetailObj.optString("total_post", "1");
                                    String postPostSection = postDetailObj.optString("post_section", "image");
                                    String postActiveStatus = postDetailObj.optString("is_active", "1");

                                    String postTotalViews = postDetailObj.optString("total_watched","0");
                                    String postTotalShare = postDetailObj.optString("total_share","0");
                                    String postTotalDownload = postDetailObj.optString("total_download","0");
                                    String postTotalReaction = postDetailObj.optString("total_reaction","0");

                                    String postTotalLike = postDetailObj.optString("total_like","0");
                                    String postTotalSmile = postDetailObj.optString("smile_reaction","0");
                                    String postTotalLaugh = postDetailObj.optString("laugh_reaction","0");
                                    String postTotalSad = postDetailObj.optString("sad_reaction","0");
                                    String postTotalLove = postDetailObj.optString("love_reaction","0");
                                    String postTotalShock = postDetailObj.optString("shock_reaction","0");

                                    int totalPostFiles = Integer.parseInt(postTotalPost);
                                    int postArrLength = postFilesArr.length();
                                    String postImageUrl = null;
                                    String postMusicUrl = null;

                                    String commonUrl = "";
                                    if(postArrLength >= 1){
                                        JSONObject dataFilesListObj = postFilesArr.optJSONObject(0);
//                                        System.out.println("post files full data... : " + dataFilesListObj);
                                        String postFileId = dataFilesListObj.optString("id");
                                        postImageUrl = dataFilesListObj.optString("image_file_path");
                                        postMusicUrl = dataFilesListObj.optString("music_file_path");
                                        System.out.println("post files full data... : " + dataFilesListObj);
                                    System.out.println("post files full data... : " + commonUrl+postMusicUrl);
                                    System.out.println("post files full data... : " + commonUrl+postImageUrl);
                                    PostList postList = new PostList();

                                    if(postImageUrl == null){

                                    Log.d(TAG, "Total Posts: "+dataListObj);

                                } catch (Exception e) {
                                    Log.d(TAG, "Post Data Error1: "+e);
                                    Toast.makeText(getActivity(), "File now found", Toast.LENGTH_LONG).show();
                                    loading = false;


                        } catch (Exception e){
                            Log.d(TAG, "Post Data Error2: "+e);
                            Toast.makeText(getActivity(), R.string.server_error, Toast.LENGTH_LONG).show();
                            loading = false;
                        try {
                            Toast.makeText(getActivity(), new JSONObject(jsonString).getString("Message"), Toast.LENGTH_LONG).show();
                        } catch (JSONException ex) {
                            Log.d(TAG, "Post Data Error3: "+ex);
                            Toast.makeText(getActivity(), R.string.server_error, Toast.LENGTH_SHORT).show();
                        loading = false;

                    // refreshing recycler view
//                    save in local memory
//                    saveArrayList(postListGlobal, "postListGlobal");

                } catch (Exception e) {
                    Log.d(TAG, "Post Data Error4: "+e);
                loading = true;
        }, new Response.ErrorListener() {
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(getActivity(), "onErrorResponse: "+ error, Toast.LENGTH_SHORT).show();
                loading = true;
                loading = false;
                Log.d(TAG, "Post Data Error5: "+error);
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String>  params = new HashMap<String, String>();
                String finalToken = "Bearer  "+token;
                params.put("Authorization", finalToken);
                params.put("Content-Type", "application/json");

                return params;
        // Add the request to the RequestQueue.

    private class CacheRequest extends Request<NetworkResponse> {
        private final Response.Listener<NetworkResponse> mListener;
        private final Response.ErrorListener mErrorListener;

        public CacheRequest(int method, String url, Response.Listener<NetworkResponse> listener, Response.ErrorListener errorListener) {
            super(method, url, errorListener);
            this.mListener = listener;
            this.mErrorListener = errorListener;
        protected Response<NetworkResponse> parseNetworkResponse(NetworkResponse response) {
            Cache.Entry cacheEntry = HttpHeaderParser.parseCacheHeaders(response);
            if (cacheEntry == null) {
                cacheEntry = new Cache.Entry();
            final long cacheHitButRefreshed = 3 * 60 * 1000; // in 3 minutes cache will be hit, but also refreshed on background
            final long cacheExpired = 24 * 60 * 60 * 1000; // in 24 hours this cache entry expires completely
            long now = System.currentTimeMillis();
            final long softExpire = now + cacheHitButRefreshed;
            final long ttl = now + cacheExpired;
            cacheEntry.softTtl = softExpire;
            cacheEntry.ttl = ttl;
            String headerValue;
            headerValue = response.headers.get("Date");
            if (headerValue != null) {
                cacheEntry.serverDate = HttpHeaderParser.parseDateAsEpoch(headerValue);
            headerValue = response.headers.get("Last-Modified");
            if (headerValue != null) {
                cacheEntry.lastModified = HttpHeaderParser.parseDateAsEpoch(headerValue);
            cacheEntry.responseHeaders = response.headers;
            return Response.success(response, cacheEntry);
        protected void deliverResponse(NetworkResponse response) {
        protected VolleyError parseNetworkError(VolleyError volleyError) {
            Log.d(TAG, "Post Data volleyError: "+volleyError);
            return super.parseNetworkError(volleyError);
        public void deliverError(VolleyError error) {

and Adapter Class

package com.example.ProjectName;

public class HomeFragmentAdapter extends RecyclerView.Adapter <HomeFragmentAdapter.HomeViewHolder>{

    //    private ArrayList<Integer> dataList;
    private List<PostList> postListGlobal;
    Context context;
    private RecyclerViewItemListener callback;
    FFmpeg ffmpeg;
    String callingPage;

    public HomeFragmentAdapter(List<PostList> postListGlobal, RecyclerViewItemListener callback, String callingPage) {
        this.postListGlobal = postListGlobal;
        this.callback = callback;
        this.callingPage = callingPage;
//        setHasStableIds(true);

    public HomeFragmentAdapter.HomeViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View root = null;
        context = parent.getContext();
        root = LayoutInflater.from(parent.getContext()).inflate(R.layout.adapter_home_tile_list, parent, false);
        return new DataViewHolder(root);

    public void onBindViewHolder(@NonNull HomeFragmentAdapter.HomeViewHolder holder, int position) {
        if (holder instanceof DataViewHolder) {
            final PostList postList = postListGlobal.get(position);

            String imageUrl = postList.getImagePath();
//            String imageUrl = Constant.SERVER_URL+"/"+postList.getImagePath();
            String musicUrl = postList.getMusicPath();
//            String musicUrl = Constant.SERVER_URL+"/"+postList.getMusicPath();
            Log.d(TAG, "Post url: "+imageUrl+" -- "+musicUrl);
//            int totalMusicTime = getDurationVal(musicUrl, "second");

            holder.thumbnail.setOnClickListener(new View.OnClickListener() {
                public void onClick(View view) {
                    Log.d("homeView", "screenName : "+callingPage);
                        Log.d("homeView", "screenName : "+position);
                        Intent intent = new Intent(context, MainViewActivity.class);
                        intent.putExtra("loginFrom", "homeView");
                        intent.putExtra("postDataObj", postList.getPostDataObject().toString());
                        intent.putExtra("postPosition", ""+position);
                        intent.putExtra("tabId", "1");

            Drawable mDefaultBackground = context.getResources().getDrawable(R.drawable.influencers);
            CircularProgressDrawable circularProgressDrawable = new CircularProgressDrawable(context);
                    .listener(new RequestListener<Drawable>() {
                        public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
//                            progressBar.setVisibility(View.GONE);
                            return false;

                        public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
//                            progressBar.setVisibility(View.GONE);
                            return false;
            //Do whatever you want. Or nothing !!

    public int getItemCount() {
        return postListGlobal.size();

    class DataViewHolder extends HomeViewHolder {
        public DataViewHolder(View itemView) {


    class ProgressViewHolder extends HomeViewHolder {
        public ProgressViewHolder(View itemView) {

    class HomeViewHolder extends RecyclerView.ViewHolder {
        public TextView postTitle, postTime, postWatch, postReaction;
        public ImageView thumbnail;
        public HomeViewHolder(View itemView) {
            postTitle = itemView.findViewById(;
            postTime = itemView.findViewById(;
            postWatch = itemView.findViewById(;
            postReaction = itemView.findViewById(;
            thumbnail = itemView.findViewById(;
    public long getItemId(int position) {
        return position;
    public int getItemViewType(int position) {
        return position;
    public void addNullData() {
    public void removeNull() {
    public void addData(List<PostList> postLists) {

After trying everything, I was still not able to resolve the issue. Any help/suggestions are welcome. Let me know If I left out any needed code--if so I can update it here.

`postListGlobal.add(postList);` below this line add ` homeFragmentAdapter.notifyDataSetChanged();` and remove `  homeFragmentAdapter.removeNull(); homeFragmentAdapter.addData(postListGlobal);homeFragmentAdapter.notifyDataSetChanged();` this code.Because in this case  list added twice without notifying datasetchange check with your code by removing this.

Recyclerview duplicated items on scroll, Do you guys have any idea of what's happening? share. Share a link to this question. Copy link. CC BY-SA 3.0 � improve this question follow. asked Mar 26 ' 16� i have 5 tabs in my appe in each tabs items are displayed. but when i moved from tab to tab,or scrolling recycler view, Doubling the number of items Adapter class: package com.narsis.countriesandcontinents.mainPage;&hellip;

postListGlobal.clear(); just clear tha arraylist before add .

how to stop the items duplication in recyclerView android, how to stop the items duplication in recyclerView android. Actually my problem is when I click the item it go to a DetailsFragment. LENGTH_SHORT).show(); return view; } Front End Web Development � Full Stack JavaScript � Beginning Python � UX: Interaction Design � Digital Literacy � View all 47 Tracks. When I update the model, the recyclerView duplicates the items in the recyclerView which you can see in the image below: public void checkedListener (CompoundButton buttonView, boolean isChecked) { Timber.d ("The active switch result is: " + isChecked); if (isActive () != isChecked) { //Update realm only if value has changed realm.beginTransaction (); setActive (isChecked); realm.commitTransaction (); Timber.d ("Active switch updated"); } }

postListGlobal.clear() before adding new list to the adapter. And then notifyDataSetChanged() to let adapter know of the changes.

RecyclerView items duplicate and constantly changing, recyclerview showing duplicate items android recyclerview show only 10 items recycler view and it works except that the first 3 items repeat every 7 items. how to stop the items duplication in recyclerView android Actually my problem is when I click the item it go to a DetailsFragment. But when I return back to my ItemListFragment the items number is increased and duplication is occurred.

1. Click anywhere in your pivot. 2. Design Tab > Report Layout > Repeat All Item Labels (This will repeat item labels for all items) 3. If you want to repeat only for selective item labels -. 3.1 Right click on that item label. 3.2 Choose Field Settings. 3.3 Layout and Prints > Repeat Item Labels.

Issues and steps to reproduce. RecyclerView is not showing all items when list is long when used with FlexboxLayoutManager. Wrap RecyclerView with android:nestedScrollingEnabled="false" inside NestedScrollView. Create and add FlexboxLayoutManager to RecyclerView. Load recycler view with long list of items.

I am developing a POS system in android and trying to list images from an api into a fragment with a recyclerview.when i debug i see the list returned but not in the android code.what more can i do to show the information in my layout.maybe i'm doing something wrong. the main activity is supposed to load the categorylist activity. categorylist is using both categoylistrecyclerview and

  • You missed a lot of posts on stackoverflow where your problem was reported earlier.
  • @blackapps, I saw many posts related to this but couldn't resolved. Any link post are welcome.
  • Do first thing it put a break point on start of constructor of HomeFragmentAdapter and then check the size and data of postListGlobal list. Then you will know that if the adapter is creating problem or you are sending duplicate data to adapter. Once we have clear on this point. Then we can go further specifically to find out data duplication.This is the correct way to do problem solving step by step.
  • I will try and test it and let you post here.
  • Full code is already shared. Only modal part is remaining, do you want to see that ?
  • yes,I need model file to debug all that to tell the solution