Reputation: 24213
I have an activity, where in i have a button (Visible) and an EditText(invisible).
When I click on button, edit text becomes visible. Now if I close my app, I want this state to be saved. I want to save the visible state of Edit Text.
I looked up the web, and it states that if I have onSaveInstanceState overridden in the activity then it should be alright.
Inside the onSaveInstanceState, I am just doing a call to super function.
In my onCreate method, I have super.onCreate.
Is there anything else that needs to be done?
Thanks
Upvotes: 1
Views: 2207
Reputation: 11191
You can retrieve the value from onSaveInstanceState when the configuration changes (e.g. rotation) but when you close your app (e.g back button) then you need to retrieve the state from the persistence storage like shared preferences.
// obtain shared preferences
SharedPreferences preferences = getSharedPreferences("prefs_file_name", MODE_PRIVATE);
// Update shared preferences file
@Override
public void onPause() {
sharedPreferences.Editor prefsEditor = mSharedPreferences.edit();
prefsEditor.putInt("visibility", mEditText.getVisibility());
super.onPause();
}
Then read it on onResume()
int visibility = preferences.getInt("visibility", 0);
mEditText.setVisibility(visibility);
Upvotes: 3
Reputation: 134684
EDIT: FYI, this answer assumes this is to save state across configuration changes -- not persistent state saving.
Keep a boolean value somewhere, and save/restore that when necessary. For example:
private static final String EDIT_TEXT_VISIBLE = "edit_text_visible";
private boolean mEditTextVisible;
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean(EDIT_TEXT_VISIBLE, mEditTextVisible);
}
public void onCreate(Bundle savedState) {
super.onCreate(savedState);
// Do your view initialization...
// If there's saved state, restore the state that you saved,
// and apply it to the EditText.
if (savedState != null) {
mEditTextVisible = savedState.getBoolean(EDIT_TEXT_VISIBLE);
mEditText.setVisibility(mEditTextVisible ? View.VISIBLE : View.INVISIBLE);
}
}
Upvotes: 3
Reputation: 24998
Why do you forget the part where you put the data in the Bundle in onSaveInstanceState and retrieve it in onCreate?
You dont just call the super method in onSaveInstance state, you put your data in the Bundle also.
The other quick option is to store these values in a SharedPreference
Upvotes: 1