我有一个带有两个单选按钮的无线电组。我想选择一个单选按钮并点击保存,这样当我返回时,将选择相同的单选按钮。问题是,即使在我点击保存后,onCreate中的共享偏好总是返回null。我知道save函数正在执行,因为toast运行并且我在控制台中打印了System.out.println。
public void saveSettings(View view)
{
Toast.makeText(getApplicationContext(), "Settings Saved", Toast.LENGTH_LONG).show();
//DETERMINE WHICH RADIO BUTTON IS SELECTED
RadioButton lbSetting = (RadioButton)findViewById(R.id.weightSettingLB);
RadioButton kgSetting = (RadioButton)findViewById(R.id.weightSettingKG);
if(lbSetting.isChecked())
{
weightSetting = "lb";
}
if(kgSetting.isChecked())
{
weightSetting = "kg";
}
System.out.println("The " + weightSetting + " radio button has been selected.");
//SAVE WEIGHT SETTING BETWEEN LB/KG
settingsPrefString = getSharedPreferences(weightSetting, 0);
SharedPreferences.Editor editor = settingsPrefString.edit();
editor.putString("weightSetting", weightSetting);
editor.commit();
}
在我的onCreate中,我尝试将保存的数据检索为
if(settingsPrefString != null)
{
weightSetting = settingsPrefString.getString("weightSetting", "Couldn't load data!");
}
if(settingsPrefString == null)
{
System.out.println("settingsPrefString is NULL!");
}
即使在我点击保存后,共享偏好也始终返回为null。
答案 0 :(得分:2)
在您需要时调用这些函数:
private void savePreferences(String key, String value){
SharedPreferences sharedPreferences = getSharedPreferences("weightSetting", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
private String loadPreferences(String key){
SharedPreferences sharedPreferences = getSharedPreferences("weightSetting", MODE_PRIVATE);
String load = sharedPreferences.getString(key, "");
return load;
}
}
例如:
savePreferences("selected", "lb");
和
String s = loadPreferences("selected);
答案 1 :(得分:1)
你正在做的错误是在saveSettings方法中。在为第一个创建共享首选项时,您没有为其分配常量名称,因为您已使用变量作为名称,因此请更改它。为相同的
创建一个全局字符串常量//SAVE WEIGHT SETTING BETWEEN LB/KG
settingsPrefString = getSharedPreferences(weightSetting, 0);
SharedPreferences.Editor editor = settingsPrefString.edit();
到
public static final String SETTINGS_PREFERENCE = "SETTINGS_PREFERENCE"
SharedPreference settingsPrefString
//your code
//saveSettings method
//SAVE WEIGHT SETTING BETWEEN LB/KG
settingsPrefString = getSharedPreferences(SETTINGS_PREFERENCE , Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settingsPrefString.edit();
如果查看更改,则使用两个常量,这使代码更易读和可访问。
下次在onCreate()方法中,您还必须添加
settingsPrefString = getSharedPreferences(SETTINGS_PREFERENCE , Context.MODE_PRIVATE);
if(settingsPrefString != null)
{
weightSetting = settingsPrefString.getString("weightSetting", "Couldn't load data!");
} else {
System.out.println("settingsPrefString is NULL!");
}
答案 2 :(得分:0)
替换
settingsPrefString = getSharedPreferences(weightSetting, 0);
使用
settingsPrefString = getSharedPreferences(weightSetting, Context.MODE_PRIVATE);
这也有帮助
settingsPrefString = PreferenceManager.getDefaultSharedPreferences(this);
并关注this link