Search code examples
javaandroidandroid-studioandroid-developer-api

storing & loading your apps previous state


I am using static session_counter to store the data, yes the data I want to retrieve when app is opened is a INTEGER

 private static int session_counter = 0;

MY app state enter image description here

AFTER USER PERFORMED AN ACTION THE SESSION COUNTER SHOWS 1, BUT WHEN THE APPLICATION IS CLOSED AND RE-OPENED AGAIN THE COUNTER IS SET TO 0

I WANT THAT SESSION COUNTER TO BE THE SAME AS PREVIOUS STATE TILL THE SPECIFIC CONDITION IS MET


Solution

  • For applications such as this you need a way where you can persist the data between each session. as a previous answer mentioned shared preferences is the most effective way to do it.

    Other alternatives exist as

    1. Room
    2. A remote database (Firebase) etc.

    The structure will be somewhat like this

    ```
    
    // Create object of SharedPreferences.
            SharedPreferences sharedPref = getSharedPreferences("mypref", 0);
    
            //now get Editor
            SharedPreferences.Editor editor = sharedPref.edit();
    
            //put your value
            editor.putString("session_value", required_Text);
    
            //commits your edits
            editor.commit();
    
           // Its used to retrieve data
           SharedPreferences sharedPref = getSharedPreferences("mypref", 0);
           String name = sharedPref.getString("session_value", "")
    
           ```
    

    In your case it will be like

    
    textView.text= sharedPref.getString("session_value", "")
    
    if(condition){
    editor.putString("session_value", required_Text);
    }