Search code examples
androidandroid-recyclerviewandroid-adapterandroid-scrollview

Recyclerview Position changing to first position when I Update


I am using onLoadMoreListener when i scroll RecyclerView. It will update the RecyclerView data when you scroll to bottom. After updating the Recyclerview data. The Recyclerview goes back up to the top. Ideally, I would like to retain the position in the RecyclerView. Any thoughts on how I should go about doing this?

mAdapter.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
              new GroupData().execute();
            }
        });


InnerClass

    public static class GroupData extends AsyncTask<Void, Void, Void> {

        @Override
        protected Void doInBackground(Void... voids) {
           try{
             GroupList gm = new GroupList();
             .....
             groupvalues.add(gm);
            } catch (Exception e){
               Log.d("Grouplist ", e.toString());
           }
          return null;
        }
        @Override
        protected void onPostExecute(Void aVoid) {
             super.onPostExecute(aVoid);
             mAdapter = new GroupAdapter(groupvalues,mrecyclerview);
             mrecyclerview.setAdapter(mAdapter);
             progressDialog.dismiss();
             mAdapter.notifyDataSetChanged();
             }
           }
         }

Solution

  • Try this,

    public static class GroupData extends AsyncTask<Void, Void, Void> {
        int size = 0;
    
        @Override
        protected void onPreExecute() {
            size = groupvalues.size();
        }
    
        @Override
        protected Void doInBackground(Void... voids) {
            try {
                GroupList gm = new GroupList();
                .....
                groupvalues.add(gm);
            } catch (Exception e) {
                Log.d("Grouplist ", e.toString());
            }
            return null;
        }
    
        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            mAdapter.notifyItemRangeChanged(size, groupvalues.size() - size);
            progressDialog.dismiss();
        }
    }