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.
Asked
Active
Viewed 1,145 times
0
-
1It is better to use onSaveInstanceState() for storing state of an Activity. See http://stackoverflow.com/questions/4096169/onsaveinstancestate-and-onrestoreinstancestate – petrsyn Oct 26 '12 at 14:40
-
did you mean storing the last value of your variable – Lucifer Oct 26 '12 at 14:41
-
I would recommend onStop at the latest. If the data is crtitical, I would recommend saving it immediately instead of waiting for cleanup – Joe Plante Oct 26 '12 at 15:03
2 Answers
1
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

Alex
- 379
- 4
- 14
-
Lot more definitive that the previous answer, and corrected some of my code. – 8BitSensei Oct 26 '12 at 15:02
-
My Variable is a Boolean, what do i put in place of putString() or what changes should i make? – 8BitSensei Oct 26 '12 at 15:09
-
-
Brilliant! and sorry to be a bother but any idea on how to call the editor.commit() in a different activity as i cannot make it static? – 8BitSensei Oct 26 '12 at 15:22
0
-
I was trying to get Shared preference to work earlier, it must of just been some bad coding that through me off the trail, but now i know that i'm looking in the right direction, thank-you. – 8BitSensei Oct 26 '12 at 14:52