I am having 5 radiobuttons in my application and i want to save their states so that when i exit and then come back to the application then i see the same button clicked which was clicked prior to my exiting the application
Following is my code for saving the state
private int flag1 = true;
private void save(final boolean isChecked) {
SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("check", isChecked);
editor.commit();
}
private boolean load() {
SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
return sharedPreferences.getBoolean("check", true);
}
protected void onPause() {
super.onPause();
save(!flag1);
SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
}
@Override
protected void onResume() {
super.onResume();
save(load());
Toast.makeText(getApplicationContext(),""+load(), Toast.LENGTH_LONG).show();
}
I am calling the save method from inside the onCheckedChangeListener for every radiobutton but nothing happens.
Is there any other method of using sharedpreferences ??
you are saving all button state using same key(check). Try something like this
In load method loop through all radiobutton
UPDATE
In RadioGroup only one button is checked at a time. so store check button id instead.
and use following code to restore
You could also try override:
methode
you can use this code
and here is layout:
use
SharedPreferences
in a separate helper class. That way you could initialize theSharedPreferences
in the start of the activity and check if there were any values present there.You can see the code example here. Doing this ... as I said in the
onCreate
you could check if theSharedPreferences
has any value. Check the full source code here.save your radio button value using shared preferences like this
And to load this you have to set it to default true/false.
and to use this write down below code