问题
I want to have the status of a checkbox be saved into my prefs.
I set a listener on the checkbox, and if it is checked I do a prefs.putBoolean("cbstatus", true), and it is it unchecked i do a prefs.putBoolean("cbstatus", false);
Trouble is, in my onStart() when I get prefs, my Boolean getcbstatus = prefs.getBoolean("cbstatus", false); will always return a true, regardless of how my listener should have set that status previously.
What am I doing wrong? I have working prefs for other things like spinners, textviews, and edit texts, but what should be the simplest type (a boolean) is giving me a hard time.
I've even tried taking out all code related to listeners and pref setting for this checkbox, so that the only code in the entire activity that deals with the checkbox is in the line
Boolean getcbstat = prefs.getBoolean("cbon", false);
if (getcbstat = true) {
cb1.setChecked(true);
}
else {
cb1.setChecked(false);
format.setVisibility(View.VISIBLE);
}
Since there is no cbon preference (i deleted them all), it should return false by default and the box should be unchecked since. cb1, of course, is the name of my checkbox.
Any ideas?
Update on the code:
OnClickListener cb = new OnClickListener() {
public void onClick(View v) {
if (cb1.isChecked()) {
prefs.putBoolean("cbon", true);
}
else {
prefs.putBoolean("cbon", false);
}
}
};
And in the onStart():
Boolean getcbstat = prefs.getBoolean("cbon", false);
cb1.setChecked(getcbstat);
回答1:
You've accidentally assigned it to true in your if statement.
Change it to this
if (getcbstat == true)
[Edit -- How to use shared preferences (instead of Java's preferences class)] How to use SharedPreferences:
private SharedPreferences mPref;
@Override
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
mPref = getSharedPreferences("my_prefs_file", MODE_PRIVATE);
//Other onCreate code goes here...
}
//Example of where you might want to save preferences
@Override
protected void onPause() {
super.onPause();
Editor prefEdit = pref.edit();
prefEdit.putBoolean("cbon", true);
prefEdit.commit();
}
When you need to read it later:
//Example of where you might want to save preferences
@Override
protected void onResume() {
super.onResume();
boolean getcbstat = pref.getBoolean("cbon", false);
}
It would probably be a good idea to make the pref variable class level and get the preferences object in the onCreate section. Change "my_prefs_file" to whatever you like, but remember that that string is what you will use to access that that particular set of preferences from within your application. I also recommend using constants instead of raw strings for the access keys (like "cbon").
Good luck:)
来源:https://stackoverflow.com/questions/3869063/android-boolean-preference-problem