【问题标题】:SharedPreferences duplicate saved dataSharedPreferences 重复保存的数据
【发布时间】: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();

标签: android sharedpreferences


【解决方案1】:

我将您的问题解释如下:您想将 ID("5") 保存到 sharedpreferences,当您检索它时,它应该返回为 ",5"。这意味着您可以在 sharedprefs 中保存 "5" 并在检索时添加 ,,或者保存包含逗号 (",5") 的 id。

/* Storing the id */
String FavoritsKey = "com.test";
String valueToSave = "" + selected.ID; // we'll store "5" in sharedPreferences
Editor edit = preferences.edit();    
edit.putString(FavoritsKey, valueToSave);
edit.commit(); //almost the same as apply, you can read the API docs if you want

/* Retrieving the id and prefix it */
String valueToRetrieve = preferences.getString(FavoritsKey, ""); // retrieve "5"
valueToRetrieve = "," + valueToRetrieve; // well prefix the "5" with "," for ",5"

反之亦然

/* Storing the id with prefixed comma*/
String FavoritsKey = "com.test";
String valueToSave = "," + selected.ID; // we'll store ",5" in sharedPreferences
Editor edit = preferences.edit();    
edit.putString(FavoritsKey, valueToSave);
edit.commit(); //almost the same as apply, you can read the API docs if you want

/* Retrieving the id with a prefixed comma */
String valueToRetrieve = preferences.getString(FavoritsKey, ""); // retrieve ",5"

但是,您的代码完全按照应有的方式运行。

preferences.edit().putString(FavoritsKey,  preferences.getString(FavoritsKey, "")+","+ selected.Id).apply();

让我们仔细看看。在 sharedPreferences 中,在键 FavoritsKey 上,您存储:

preferences.getString(FavoritsKey, "")+","+ selected.Id) 
//lets assume ",5" was stored initially
//outcome is ",5" + "," + 5 => thats ",5,5"
//and the next time another ",5" is added, and so on, etc...

【讨论】:

    猜你喜欢
    • 2013-09-27
    • 1970-01-01
    • 1970-01-01
    • 2018-08-08
    • 1970-01-01
    • 2015-04-29
    • 1970-01-01
    • 1970-01-01
    • 2023-03-09
    相关资源
    最近更新 更多