android-从共享首选项放置和获取String数组
我需要在共享首选项中保存一些字符串数组,然后再获取它们。我尝试了这个:
playlist= myPrefs.getString(PLAYLISTS, "playlists");,其中播放列表是String
并得到:
playlist= myPrefs.getString(PLAYLISTS, "playlists");,其中播放列表是String,但无法正常工作。
我怎样才能做到这一点 ? 谁能帮我?
提前致谢。
5个解决方案
92 votes
您可以像这样创建自己的数组的String表示形式:
StringBuilder sb = new StringBuilder();
for (int i = 0; i < playlists.length; i++) {
sb.append(playlists[i]).append(",");
}
prefsEditor.putString(PLAYLISTS, sb.toString());
然后,当您从SharedPreferences获取字符串时,只需像下面这样解析它:
String[] playlists = playlist.split(",");
这应该做的工作。
Egor answered 2019-12-28T06:26:42Z
28 votes
从API级别11开始,您可以使用putStringSet和getStringSet来存储/检索字符串集:
SharedPreferences pref = context.getSharedPreferences(TAG, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putStringSet(SOME_KEY, someStringSet);
editor.commit();
SharedPreferences pref = context.getSharedPreferences(TAG, Context.MODE_PRIVATE);
Set someStringSet = pref.getStringSet(SOME_KEY);
MikeL answered 2019-12-28T06:27:02Z
8 votes
您可以使用JSON将数组序列化为字符串并将其存储在首选项中。 在这里查看我的答案和示例代码以获取类似的问题:
如何编写代码以在Android中对数组进行共享首选项?
Jeff Gilfelt answered 2019-12-28T06:27:29Z
0 votes
HashSet mSet = new HashSet<>();
mSet.add("data1");
mSet.add("data2");
saveStringSet(context, mSet);
哪里
public static void saveStringSet(Context context, HashSet mSet) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = sp.edit();
editor.putStringSet(PREF_STRING_SET_KEY, mSet);
editor.apply();
}
和
public static Set getSavedStringSets(Context context) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
return sp.getStringSet(PREF_STRING_SET_KEY, null);
}
private static final String PREF_STRING_SET_KEY = "string_set_key";
Dan Alboteanu answered 2019-12-28T06:27:53Z
0 votes
如果需要更多信息,请使用此简单功能优先存储阵列列表。
public static void storeSerializeArraylist(SharedPreferences sharedPreferences, String key, ArrayList tempAppArraylist){
SharedPreferences.Editor editor = sharedPreferences.edit();
try {
editor.putString(key, ObjectSerializer.serialize(tempAppArraylist));
editor.apply();
} catch (IOException e) {
e.printStackTrace();
}
}
以及如何从首选项获取存储的arraylist
public static ArrayList getSerializeArraylist(SharedPreferences sharedPreferences, String key){
ArrayList tempArrayList = new ArrayList();
try {
tempArrayList = (ArrayList) ObjectSerializer.deserialize(sharedPreferences.getString(key, ObjectSerializer.serialize(new ArrayList())));
} catch (IOException e) {
e.printStackTrace();
}
return tempArrayList;
}
Hitesh Tarbundiya answered 2019-12-28T06:28:18Z