0

how i can save my last position in RecyclerView adapter after app closed and restore it after return to app

 RecyclerList.add(m);
        messageAdapter = new MessageAdapter(context, RecyclerList, leftUser, rightUser,  this);
        recyclerView.setAdapter(messageAdapter);
    }

    public void LoadData() {
        if (isNetworkAvailable()) {
            if (i < arrSplit.length) {
                recyclerListSize = RecyclerList.size();

                String temp = arrSplit[i];

                Data m = new Data(temp);

                RecyclerList.add(m);

                Objects.requireNonNull(recyclerView.getAdapter()).notifyItemInserted(recyclerListSize);
                recyclerView.smoothScrollToPosition(recyclerListSize);


                i++;
            } else {
              //  
Mahmoud Abu Alheja
  • 3,343
  • 2
  • 24
  • 41

1 Answers1

0

Depending on what I understand you want store last position of item visible in your RecyclerView, so when back to app again scroll to last position before closed app/activity

First of all you can get last position from LayoutManger of RecyclerView like this

//define LinearLayoutManager object as global because we want to use in another method 
linearLayoutManager=new LinearLayoutManager(this);
recyclerView.setLayoutManager(linearLayoutManager);

and now we want to get last position and store it if activity is closed or go to background using life cycle activity call back

if you want know more about activity life cycle go to this

so inside onPause in your activity add store last position using SharedPrefrane

@Override
    protected void onPause() {
        super.onPause();            

        SharedPreferences preferences =getSharedPreferences("Pref",MODE_PRIVATE);

        //get last position Visible Item Position
        int lastPos= linearLayoutManager.findLastCompletelyVisibleItemPosition();

        //store lastPos
        preferences.edit().putInt("lastPos",lastPos).apply();

    }

know we store last position every time activity go to background or app closed

and after get data and set Adapter, retrieve the last position by add and call this method

private int getLastItemPosition(){

        SharedPreferences preferences =getSharedPreferences("Pref",MODE_PRIVATE);

        return preferences.getInt("lastPos",0);
    }
Mahmoud Abu Alheja
  • 3,343
  • 2
  • 24
  • 41