Search code examples
javaandroidandroid-lifecycle

How to call a method just before an app is closed?


I have a variable who contains data that can change when user is using app. My goal is to store those data in SharedPrefs just before user is closing app, I was thinking about something like

OnStop()  {
Preferences.edit()... }

but i don't know the correct syntax ... thanks in advance guys


Solution

  • Save your data in SavedPrefs in onStop Method.

    Syntex will be like

    In onStop Method

    @Override
    protected void onStop() {
        super.onStop();
        SharedPreferences saved_values = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        SharedPreferences.Editor editor = saved_values.edit();
        edit.putString("key", "stringToBeSaved")
    
        editor.commit();
    }
    

    And then to retrive your data in onCreate method

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        SharedPreferences saved_values = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        String foo = saved_values.getString("key", "default_string");
    }
    

    Remember the key should be same.

    For more info check out Android docs on
    Shared Preferences: Save key-value data
    Android Lifecycle: Understand the Activity Lifecycle