I am trying to save the state of my toggle button when the app got killed and relaunched via SharedPreferences.
I can see on /data/data/myapp/shared_prefs that the xml with the value true/false is written to, but I am stuck on letting the code read the preference every time I kill and restart the app.
The button just resets to the default state, true in my case. In my case, I am running it on a fragment; so I had to use:
final SharedPreferences preferences = this.getActivity().getSharedPreferences("tg1pref",0);
Here is my code:
boolean on;
public SharedPreferences preferences;
final ToggleButton toggleButton1 = (ToggleButton) v.findViewById(R.id.toggleButton1);
final SharedPreferences preferences = this.getActivity().getSharedPreferences("tg1pref",0);
boolean tg1pref = preferences.getBoolean("tg1pref", true);
if (tg1pref = true) {
toggleButton1.setChecked(true);
} else {
toggleButton1.setChecked(false);
}
toggleButton1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if((toggleButton1.isChecked())) {
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("tg1pref", true); // value to store
editor.commit();
} else {
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("tg1pref", false); // value to store
editor.commit();
}
}
});
Thanks for the help!
Solved with t0mm13b method:
if (tg1pref = true) {
//That should be:
if (tglpref){ // Meaning and same as if (tglpref == true)
This line:
That should be:
There was a typo in there!