【发布时间】:2014-08-09 23:46:16
【问题描述】:
如果我的 ID = 5 并且我想保存在 SharedPreferences 我得到结果 5,5 这是错误的,我使用的代码是
String FavoritsKey = "com.test";
SharedPreferences preferences = getApplicationContext().getSharedPreferences("SpeakEgyptPreferences", Context.MODE_PRIVATE);
preferences.edit().putString(FavoritsKey, preferences.getString(FavoritsKey, "")+","+ selected.Id).apply();
例如
我第一次想保存 5 => 应该得到 string =",5" 但我得到 ",5,5" 等等
如何解决重复
【问题讨论】:
-
该代码按预期运行。你到底想做什么?
-
你的问题不清楚,预期的输出是什么?
-
preferences.getString(FavoritsKey, "")+","+ selected.Id说:append to the previously saved value: "," followed by the current id- 因此,下一个值(假设 id = 5)将是:5,5,5。下一个:5,5,5,5。以此类推 -
@FrankN.Stein 如何解决这个问题
-
用这个 String FavoritsKey = "com.test"; 改变你的代码SharedPreferences 首选项 = getApplicationContext().getSharedPreferences("SpeakEgyptPreferences", Context.MODE_PRIVATE); preference.edit().putString(FavoritsKey, preferences.getString(FavoritsKey, "")+","+ selected.Id).commit();