从共享首选项中放入并获取String数组

问题描述 投票:52回答:5

我需要在共享首选项上保存一些字符串数组,然后才能获取它们。我试过这个:

prefsEditor.putString(PLAYLISTS, playlists.toString());,其中播放列表是String[]

得到:

playlist= myPrefs.getString(PLAYLISTS, "playlists");播放列表是String,但它不起作用。

我怎样才能做到这一点 ?谁能帮我?

提前致谢。

android arrays string sharedpreferences
5个回答
92
投票

您可以像这样创建自己的数组的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时,只需解析它:

String[] playlists = playlist.split(",");

这应该做的工作。


28
投票

从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<String> someStringSet = pref.getStringSet(SOME_KEY);

8
投票

您可以使用JSON将数组序列化为字符串并将其存储在首选项中。有关类似问题,请参阅我的答案和示例代码:

How can write code to make sharedpreferences for array in android?


0
投票
HashSet<String> mSet = new HashSet<>();
                mSet.add("data1");
                mSet.add("data2");
saveStringSet(context, mSet);

哪里

public static void saveStringSet(Context context, HashSet<String> mSet) {
    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
    SharedPreferences.Editor editor = sp.edit();
    editor.putStringSet(PREF_STRING_SET_KEY, mSet);
    editor.apply();
}

public static Set<String> 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";

0
投票

如果你想要更多信息qazxsw poi,可以使用这个简单的函数优先存储数组列表

Click here

以及如何从偏好中获取存储的arraylist

 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();
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.