【问题标题】:How to retrieve Strings from SharedPreferences in the same order as it is stored如何以与存储顺序相同的顺序从 SharedPreferences 中检索字符串
【发布时间】:2014-07-17 19:04:50
【问题描述】:

我像这样将字符串放在 SharedPreferences 中

SharedPreferences preferences = getActivity().getSharedPreferences("Music_playlist", Context.MODE_PRIVATE);

                        SharedPreferences.Editor editor = preferences.edit();
                        editor.putString(Song_name, Song_name);
                        editor.commit();

当我尝试从 SharedPreferences 中检索字符串时,它不会保持与存储在 sharedPreferences 中的相同顺序

 SharedPreferences prefs = getActivity().getSharedPreferences("Music_playlist", Context.MODE_PRIVATE);
    Map<String,?> keys = prefs.getAll();

    if(keys!=null) {

        for (Map.Entry<String, ?> entry : keys.entrySet()) {
            Log.d("data ADDED",(String)entry.getValue());
            PLAYLIST.add((String)entry.getValue());
        }
    }

我应该如何在 SharedPreferences 中存储字符串并在从中获取字符串时保持顺序

【问题讨论】:

  • 要么在单个首选项键下序列化列表,要么使用数据库。 SharePreferences 不是有序的数据存储。

标签: android hashmap set sharedpreferences entryset


【解决方案1】:

SharedPreferences 就像HashMap 一样,不会为您存储在其中的键值对提供任何排序​​。要以有序的方式存储播放列表,您需要使用单个键值对,并且该值应该是逗号分隔的歌曲名称列表。您实际上可以使用任何合适的分隔符(注意转义歌曲名称)或存储 JSON 编码数组。

这里有一些伪代码,但这并不能说明最佳实践。

SharedPreferences preferences = getActivity().getSharedPreferences("Music_playlist", Context.MODE_PRIVATE);
String playlist = preferences.getString("playlist");
playlist += "," + escapeCsv(songName);

SharedPreferences.Editor editor = preferences.edit();
editor.putString("playlist", playlist);
editor.commit();

最好将播放列表存储在数据库中。

【讨论】:

    猜你喜欢
    • 2015-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多