将 ArrayList 转换为 String 以存储在共享首选项中
Converting ArrayList to String to store in Shared Preferences
我有多个值的 ArrayList。我想将此 ArrayList 转换为 String 以保存在 sharedPreferences 中,然后我想检索 String 并将其转换回 ArrayList
请告诉我怎么做? (或任何其他存储和检索 ArrayList 的想法)
您可以使用 Google 的 GSON。
Gson is a Java library that can be used to convert Java Objects into
their JSON representation. It can also be used to convert a JSON
string to an equivalent Java object. Gson can work with arbitrary Java
objects including pre-existing objects that you do not have
source-code of.
http://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/Gson.html
https://code.google.com/p/google-gson/
你明白了:
- Store: Convert Object to JSON String -> Save string
- Retrieve: Get string -> Convert from JSON to Object
将数组列表转换为字符串:
String str = "";
for (String s : arraylist)
{
str += s + ",";
}
将字符串保存到共享首选项中:
PreferenceManager.getDefaultSharedPreferences(context).edit().putString("mystr", str).commit();
从共享首选项中获取字符串:
String str = PreferenceManager.getDefaultSharedPreferences(context).getString("mystr", "defaultStringIfNothingFound");
将字符串转换为数组列表:
List<String> arraylist = new ArrayList<String>(Arrays.asList(str.split(",")));
我有多个值的 ArrayList。我想将此 ArrayList 转换为 String 以保存在 sharedPreferences 中,然后我想检索 String 并将其转换回 ArrayList
请告诉我怎么做? (或任何其他存储和检索 ArrayList 的想法)
您可以使用 Google 的 GSON。
Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object. Gson can work with arbitrary Java objects including pre-existing objects that you do not have source-code of.
http://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/Gson.html
https://code.google.com/p/google-gson/
你明白了:
- Store: Convert Object to JSON String -> Save string
- Retrieve: Get string -> Convert from JSON to Object
将数组列表转换为字符串:
String str = "";
for (String s : arraylist)
{
str += s + ",";
}
将字符串保存到共享首选项中:
PreferenceManager.getDefaultSharedPreferences(context).edit().putString("mystr", str).commit();
从共享首选项中获取字符串:
String str = PreferenceManager.getDefaultSharedPreferences(context).getString("mystr", "defaultStringIfNothingFound");
将字符串转换为数组列表:
List<String> arraylist = new ArrayList<String>(Arrays.asList(str.split(",")));