Note that there are some explanatory texts on larger screens.

plurals
  1. POsharedpreferences don't read button state
    text
    copied!<p>I am trying to save the state of my toggle button when the app got killed and relaunched via <code>SharedPreferences</code>. </p> <p>I can see on <code>/data/data/myapp/shared_prefs</code> 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.</p> <p>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: </p> <p><code>final SharedPreferences preferences = this.getActivity().getSharedPreferences("tg1pref",0);</code></p> <p>Here is my code:</p> <pre><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(); } } }); </code></pre> <p>Thanks for the help!</p> <p><strong>Solved with t0mm13b method:</strong></p> <pre><code> if (tg1pref = true) { //That should be: if (tglpref){ // Meaning and same as if (tglpref == true) </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload