感谢您花时间聆听我的问题。 我目前正在编写一个小笔记应用程序,并将所有内容保存为共享首选项中的字符串。我现在想对笔记条目的概述进行排序,以便最新的条目始终显示在顶部。问题是,当我对笔记正文进行排序时,排序有效,但不能按日期排序。该日期以 dd.mm.yyyy 的形式作为字符串存储在共享首选项中。我怎样才能意识到这一点?
这是从sharedPref加载所有数据的方法。
public static ArrayList<Note> loadAll(Context context) {
SharedPreferences sharedPreferences = context.getSharedPreferences(STORE_PREF, Context.MODE_PRIVATE);
ArrayList<Note> notes = new ArrayList<>();
Set<String> noteIds = sharedPreferences.getStringSet(ID_KEY, null);
if (noteIds != null) {
for (String noteId : noteIds) {
notes.add(load(context, noteId));
}
}
Collections.sort(notes, new Comparator<Note>() {
@Override
public int compare(Note o1, Note o2) {
// sorting by body-string works fine yeah
return o1.getDate().compareTo(o2.getDate());
}
});
return notes;
}
这里我有两张截图。按正文排序和按日期排序
您可以将
String
日期转换为真实的 LocalDate
,然后排序:
DateTimeFormatter f = DateTimeFormatter.ofPattern("dd-MM-yyyy");
notes.sort(
(String s1, String s2) -> LocalDate.parse(s1, f).compareTo(LocalDate.parse(s2, f)));
但最好的通用方法是将日期保留为应用程序中的
LocalDate
,而不是存储为文本。