0

作为练习,我正在开发一个简单的笔记应用程序。显然,笔记必须持久保存,所以我有以下方法:

public static void saveNotesPersistently() {
    SharedPreferences.Editor editor = sharedPreferences.edit();
    HashSet<String> titleSet = new HashSet<String>();
    HashSet<String> contentSet = new HashSet<String>();
    for (int i = 0; i < Library.notes.size(); i++) {            
        String title = (Library.notes.get(i).title == null) ? "No title" : Library.notes.get(i).title;

        Log.d("Checks", "Saving note with title: " + title);

        String content = (Library.notes.get(i).content == null) ? "No content yet" : Library.notes.get(i).content;
        titleSet.add(title);
        contentSet.add(content);
    }

    Log.d("Checks", "Saving title set: " + titleSet);

    editor.putStringSet("noteTitles", titleSet);
    editor.putStringSet("noteContents", contentSet);
    editor.commit();
}

奇怪的是,第一个日志中注释标题的顺序与第二个日志中注释标题的顺序不同。显然有些事情出了问题titleSet.add(title)。我不知道为什么。有人知道这里发生了什么吗?

编辑:

所以我发现这是因为 HashSet 没有排序。这给我带来了另一个问题,因为我正在加载这样的笔记:

Set<String> noteTitles = sharedPreferences.getStringSet("noteTitles", null);
Set<String> noteContents = sharedPreferences.getStringSet("noteContents", null);

现在保存的顺序是正确的,但是加载后又出错了。不幸的是,没有类似的东西sharedPreferences.getLinkedHashSet(),那我该怎么办?

4

3 回答 3

3

改为使用LinkedHashSet可预测的迭代顺序。

见文档here

于 2013-09-16T19:49:39.283 回答
2

根据要求,这里是使用 JSONArray 进行序列化的示例。

存储数据:

SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("jsonArray", new JSONArray(list).toString());
editor.commit();

检索数据:

try {
    JSONArray jsonArray = new JSONArray(sharedPreferences.getString(
            "jsonArray", null));
    // jsonArray contains the data, use jsonArray.getString(index) to
    // retreive the elements

} catch (JSONException e) {
    e.printStackTrace();
}
于 2013-09-16T20:38:11.303 回答
0

HashSet不保证元素的顺序。TreeSet如果您需要订购元素,请考虑使用。

于 2013-09-16T19:54:15.907 回答