【发布时间】:2014-04-29 20:17:10
【问题描述】:
我使用首选项管理器来保存一些整数和布尔值。 我创建了一个 SettingsPreferences 类:
public class SettingsPreferences {
private Context mContext;
public SettingsPreferences(Context context) {
this.mContext = context;
}
public boolean isNull() {
if (PreferenceManager.getDefaultSharedPreferences(mContext) == null) {
return true;
} else {
return false;
}
}
public void setBoolean(String name, boolean value) {
PreferenceManager.getDefaultSharedPreferences(mContext).edit()
.putBoolean(name, value).apply();
}
public void setInt(String name, int value) {
PreferenceManager.getDefaultSharedPreferences(mContext).edit()
.putInt(name, value).apply();
}
public boolean getBoolean(String name, boolean defaultValue) {
return PreferenceManager.getDefaultSharedPreferences(mContext)
.getBoolean(name, defaultValue);
}
public int getInt(String name, int defaultValue) {
return PreferenceManager.getDefaultSharedPreferences(mContext).getInt(
name, defaultValue);
}}
在 Main 类的 onCreate 方法中,我添加了默认值:
mSettingsPreferences = new SettingsPreferences(getApplicationContext());
if(mSettingsPreferences.isNull() == true) {
mSettingsPreferences.setBoolean("MAX", 1);
mSettingsPreferences.setBoolean("PROGRESS", 1);
}
在片段类中,我需要加载该数据并将其显示在进度条中。 这是代码:
Thread t = new Thread() {
public void run() {
try {
sleep(100);
SettingsPreferences sett = new SettingsPreferences(mContext);
mProgBar.setMax(sett.getInt("MAX", 2));
mProgBar.setProgress(sett.getInt("PROGRESS", 1));
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
t.start();
上下文是定义的,我检查了他,进度条也是,但每次它加载我的默认值。 有什么问题?
【问题讨论】:
-
在你的setXXX方法中,编辑后必须commi (developer.android.com/reference/android/content/…)
-
除了上述评论之外,您在一个调用中使用 setBoolean ,但您在另一个调用中使用 getInt 来获取相同的键!不要初始化值,只需传入默认值!像这样的不一致是通往噩梦的道路
标签: java android default-value