Sharedpreferences With Switch Button
I have a project, i want to save state of switch button on sharedpreferences. but it not working. Switch button always off when i switch activity or close app and reopen. what wron
Solution 1:
You need to retrieve the values from shared preferences and then set the button state in onCreate
method
SharedPreferencespreferences= getPreferences(MODE_PRIVATE);
booleantgpref= preferences.getBoolean("tgpref", true); //default is trueif (tgpref = true) //if (tgpref) may be enough, not sure
{
tg.setChecked(true);
}
else
{
tg.setChecked(false);
}
Solution 2:
the onCheckedChanged-method in the end will never be called and therefore your states are not going to be saved.
The reason for this is, that you are declaring a new listener for every switch. call
saveinSp("sw1", isChecked);
in the listener of switch one or set your class as listener for the switches and handle all changes there:
switch.setOnCheckedChangedListener(this);
Post a Comment for "Sharedpreferences With Switch Button"