我在我的一个活动中使用SharedPreference,我想在另一个活动中引用相同的内容并获取其值。我这样做如下:
第1课
班级变量:
String PREFS_NAME = "Login";
SharedPreferences sp;
将值设置为SharedPreference
public void savePref(String key, boolean value) {
SharedPreferences sp = getSharedPreferences(PREFS_NAME,0);
Editor edit = sp.edit();
edit.putBoolean("loggdin", value);
edit.commit();
Toast.makeText(getApplicationContext(), "Login = " + value,
Toast.LENGTH_LONG).show();
}
第2课
班级变量:
SharedPreferences sp;
String PREFS_NAME = "Login";
在onCreate:(请同时查看评论)
SharedPreferences sp = getSharedPreferences(PREFS_NAME,0);
boolean channel = (sp.getBoolean("loggdin", true));// I get the value true or false depending on what I pass as a second argument here, pretty confused!
if (channel == true){
Toast.makeText(getApplicationContext(), "true"+channel, 10000).show();
}else {
Toast.makeText(getApplicationContext(), "false"+channel, 10000).show();
}
无法理解我哪里出错了,有什么提示吗?
答案 0 :(得分:1)
您是否尝试通过调试应用进行检查?
答案 1 :(得分:0)
试试这个我的工作代码..
public static boolean getBooleanFromSP(String key) {
// TODO Auto-generated method stub
SharedPreferences preferences = getApplicationContext().getSharedPreferences(" SHARED_PREFERENCES_NAME ", android.content.Context.MODE_PRIVATE);
return preferences.getBoolean(key, false);
}//getPWDFromSP()
public static void saveBooleanInSP(String key, boolean value){
SharedPreferences preferences = getApplicationContext().getSharedPreferences(" SHARED_PREFERENCES_NAME ", android.content.Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean(key, value);
editor.commit();
}//savePWDInSP()