有人可以帮助我看看我在这里忽略了什么吗?
问题是,这些值不会提交持久存储 - .commit()
返回true和所有内容,但值根本就没有...
public void onPause() {
super.onPause();
if (timerStarted) {
// Save the values
settings.edit().putInt(getString(beer).toString(), savedVal_beer);
settings.edit().putInt(getString(lightBeer).toString(), savedVal_ltBeer);
settings.edit().putInt(getString(strongBeer).toString(), savedVal_stBeer);
settings.edit().putInt(getString(wine).toString(), savedVal_wine);
settings.edit().putInt(getString(fortifiedWine).toString(), savedVal_fortWine);
settings.edit().putInt(getString(liqeur).toString(), savedVal_liqeur);
settings.edit().putInt(getString(spirits).toString(), savedVal_spirits);
if (counterStarted) {
settings.edit().putString(getString(R.string.key_counter_lastTypeUsed), selectedType);
}
settings.edit().commit();
if (settings.edit().commit()) {
Toast.makeText(this, "saved", Toast.LENGTH_SHORT).show();
}
}
}
我在最后添加了一个断点并使用调试器来验证要存储的变量确实存在,但是当我使用adb来提取sharedPrefs xml文件时,实际上没有保存任何值。
timerStarted
和counterStarted
都是正确的,因为它们应该是。
答案 0 :(得分:3)
您只能使用一次edit()
来电。并删除对commit()
的双重调用。
Editor editor = settings.edit();
editor.putInt(getString(beer).toString(), savedVal_beer);
editor.putInt(getString(lightBeer).toString(), savedVal_ltBeer);
editor.putInt(getString(strongBeer).toString(), savedVal_stBeer);
editor.putInt(getString(wine).toString(), savedVal_wine);
editor.putInt(getString(fortifiedWine).toString(), savedVal_fortWine);
editor.putInt(getString(liqeur).toString(), savedVal_liqeur);
editor.putInt(getString(spirits).toString(), savedVal_spirits);
if (counterStarted) {
editor.putString(getString(R.string.key_counter_lastTypeUsed), selectedType);
}
if (editor.commit()) {
Toast.makeText(this, "saved", Toast.LENGTH_SHORT).show();
}