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.
            Asked
            
        
        
            Active
            
        
            Viewed 74 times
        
    1
            
            
        - 
                    Try this -> http://stackoverflow.com/a/5688490/4018207 – AndiGeeky Nov 24 '15 at 08:25
- 
                    I am not looking to just save an activity with ListView. Also a map, etc. – JessThePest Nov 24 '15 at 08:29
- 
                    1@ JessThePest : At `onPause()` save all your data to shared preferences and restore all data on `onResume()` ..!! – AndiGeeky Nov 24 '15 at 08:36
2 Answers
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,281
- 1
- 13
- 26
- 
                    I am trying to save a whole activity not just a few Strings and booleans :S – JessThePest Nov 24 '15 at 08:34
- 
                    
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,475
- 1
- 16
- 24
 
    