我有这段代码存储"切换"列表视图中的特定项目。我使用项目的名称作为密钥。但是,getBoolean的结果始终返回第二个参数中指定的默认值。我无法弄清楚我是否错误地实现了它,或者我忽视了一些事情 为了澄清,summonerNames是Strings的一个arraylist。
MenuItem toggle = menu.findItem(R.id.postGameNotif);
SharedPreferences prefs = getApplicationContext().getSharedPreferences("summoner_prefs", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
Log.i(TAG, summonerNames.get(position));
boolean postNotif = prefs.getBoolean(summonerNames.get(position),false);
if (postNotif == true) {
toggle.setTitle("Disable post-game notifications");
Log.i(TAG,"Disabled");
editor.putBoolean(summonerNames.get(position), false);
}
else {
toggle.setTitle("Enable post-game notifications");
Log.i(TAG, "Enabled");
editor.putBoolean(summonerNames.get(position), true);
Log.i(TAG, String.valueOf(prefs.getBoolean(summonerNames.get(position),false)));
}
答案 0 :(得分:2)
问题是未在共享首选项中提交添加值。
在添加布尔值后,您错过了在共享偏好中提交更改
检查this链接
MenuItem toggle = menu.findItem(R.id.postGameNotif);
SharedPreferences prefs = getApplicationContext().getSharedPreferences("summoner_prefs", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
Log.i(TAG, summonerNames.get(position));
boolean postNotif = prefs.getBoolean(summonerNames.get(position),false);
if (postNotif == true) {
toggle.setTitle("Disable post-game notifications");
Log.i(TAG,"Disabled");
editor.putBoolean(summonerNames.get(position), false);
editor.commit()// you need to commit after adding it to sharedpref
}
else {
toggle.setTitle("Enable post-game notifications");
Log.i(TAG, "Enabled");
editor.putBoolean(summonerNames.get(position), true);
editor.commit()// you need to commit after adding it to sharedpref
Log.i(TAG, String.valueOf(prefs.getBoolean(summonerNames.get(position),false)));
}