Search code examples
javaandroidvariablesstateondestroy

Storing variables through onDestroy() event


I'm looking for a way to store the state of my variables that may have been changed from there initiation variable (ever by user activating a function or other) through the onDestroy() event so that if i turn my phone on and off my app hasn't reset the variables.


Solution

  • First of all, this is from android reference: "Note: do not count on onDestroy method being called as a place for saving data! For example, if an activity is editing data in a content provider, those edits should be committed in either onPause() or onSaveInstanceState(Bundle)"

    For saving variables you can use as said before SharedPreferences.

    Example for using inside activity class:

    SharedPreferences prefs = getSharedPreferences("preference_file_name", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = prefs.edit();
    editor.putString("variable_key", variable);
    editor.commit();
    

    For method onSaveInstanceState(Bundle) just use Bungle argument to save variables