Setsinglechoiceitems Value Doesn't Stick After Activity Kill
Solution 1:
Yes, the field is created each time anew for the respective object and since this object (i.e. the activity) is destroyed the memory holding the field is freed up as well. So the field's lifespan is bounded by that of the object. To make it continuous, you better save the value in SharedPreferences
, or in general to write it out to some storage, before destroying the activity, e.g. in onPause()
and then fetch it from those preferences in onCreate()
or onResume()
callbacks. For example:
/*--- Saving ---*/
SharedPreferences prefs =
getApplicationContext().getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE);
prefs.edit().putInt(KEY_NAME, VALUE).apply();
/*--- Retrieving ---*/int oldValue =
getApplicationContext().getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE)
.getInt(KEY_NAME, 0);
PREFERENCES_NAME
is the file name of your shared preferences file. KEY_NAME
is the key, under which you save and later retrieve the stored value. VALUE
is simply the value to save.
Hope this helps!
Solution 2:
As you are not persisting the user's choice, the choice remains in memory until activity finishes. You should save the user's choice locally using SharedPreferences or sqlite for instance!
When the activity restarts you can read the saved value and set the option as selected!
Post a Comment for "Setsinglechoiceitems Value Doesn't Stick After Activity Kill"