Android:将字符串写入 SharedPreferences 不起作用
Android: writing string to SharedPreferences does not work
我想将 HashMap 转换为 JSON,这样我就可以将它作为字符串写入我的应用程序共享首选项。
这就是我到目前为止所得到的:
HashMap<String, String> colorHashMap = new HashMap<String, String>();
colorHashMap.put("test", "test");
colorHashMap.put("ROT","#FF0000");
JSONObject colorHashMapJasonObj = new JSONObject(colorHashMap);
String JSONString = String.valueOf(colorHashMapJasonObj);
Log.v("JSON: ", JSONString);
editor.putString("standard_colors_JSON", String.valueOf(colorHashMapJasonObj));
String JSONcolorStringFromSP = prefs.getString("standard_colors_JSON", "nothting");
Log.v("JSONcolorStringFromSP: ", JSONcolorStringFromSP);
在 JSONString
我得到了正确的值。但在 JSONcolorStringFromSP
我只得到标准值。所以当我尝试将我的字符串写入我的 SharedPreferences 时会发生一些事情。但是我不知道那里出了什么问题。
您是否缺少 apply()
或 commit()
?您的 SharedPreferences
实例在哪里?这是一个完整的例子:
SharedPreferences prefs = ...;
prefs.edit().putString("somekey", "somevalue").apply();
你必须在输入一些数据后调用commit()
例如:
editor.putString("standard_colors_JSON", String.valueOf(colorHashMapJasonObj)).commit();
所有 SharedPreferences 编辑必须在实际保存之前使用 .commit()
调用。像这样:
SharedPreferences.Editor editor = GaggleApplication.getInstance().getSharedPreferences(PREFERENCE_FILE, 0).edit();
editor.putString(name, value);
editor.commit();
我想将 HashMap 转换为 JSON,这样我就可以将它作为字符串写入我的应用程序共享首选项。
这就是我到目前为止所得到的:
HashMap<String, String> colorHashMap = new HashMap<String, String>();
colorHashMap.put("test", "test");
colorHashMap.put("ROT","#FF0000");
JSONObject colorHashMapJasonObj = new JSONObject(colorHashMap);
String JSONString = String.valueOf(colorHashMapJasonObj);
Log.v("JSON: ", JSONString);
editor.putString("standard_colors_JSON", String.valueOf(colorHashMapJasonObj));
String JSONcolorStringFromSP = prefs.getString("standard_colors_JSON", "nothting");
Log.v("JSONcolorStringFromSP: ", JSONcolorStringFromSP);
在 JSONString
我得到了正确的值。但在 JSONcolorStringFromSP
我只得到标准值。所以当我尝试将我的字符串写入我的 SharedPreferences 时会发生一些事情。但是我不知道那里出了什么问题。
您是否缺少 apply()
或 commit()
?您的 SharedPreferences
实例在哪里?这是一个完整的例子:
SharedPreferences prefs = ...;
prefs.edit().putString("somekey", "somevalue").apply();
你必须在输入一些数据后调用commit() 例如:
editor.putString("standard_colors_JSON", String.valueOf(colorHashMapJasonObj)).commit();
所有 SharedPreferences 编辑必须在实际保存之前使用 .commit()
调用。像这样:
SharedPreferences.Editor editor = GaggleApplication.getInstance().getSharedPreferences(PREFERENCE_FILE, 0).edit();
editor.putString(name, value);
editor.commit();