1

I would like my application to save state after it already has loaded once. For example in one of my activities I have a ListView. If the user scrolls it, and than switches activities, I wish for them to go back to the ListView activity and have the same scrolling position. I noticed that pressing the back button goes back to a saved version of the state. This is the exact kind of save I want (where it saves the state of the previous activity). Except I want to do this from anywhere in the application, not just when the back button is pressed... Please help me.

Moudiz
  • 6,775
  • 18
  • 67
  • 139
JessThePest
  • 155
  • 1
  • 11

2 Answers2

2

You have to override onSaveInstanceState(Bundle savedInstanceState) and store the values you want to save in Bundle object as name value pair.

  @Override public void onSaveInstanceState(Bundle savedInstanceState) 
    {           
    super.onSaveInstanceState(savedInstanceState); 
    savedInstanceState.putBoolean("position", 12); 
     savedInstanceState.putString("Name", "John");

           }

also you have to override onRestoreInstanceState() where you'd extract the values:

@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
  super.onRestoreInstanceState(savedInstanceState);
  boolean myPosition=savedInstanceState.getBoolean("position");
  String name= savedInstanceState.getString("Name");
}

see this link for help LINK

Community
  • 1
  • 1
Amitabh Sarkar
  • 1,221
  • 1
  • 11
  • 25
0

It can be done with the saveInstanceState() and onRestoreInstanceState() methods. The first one called near onPause(), the second called before onResume(). To save the state of a view, call onSaveInstanceState() from view. For example, listview.onSaveInstnceState(); Here's a detailed article https://futurestud.io/blog/how-to-save-and-restore-the-scroll-position-and-state-of-a-android-listview

RexSplode
  • 1,347
  • 1
  • 11
  • 22