Android 将 LocalDate 写入和读取 SharedPreferences 麻烦

Android Writing and reading LocalDate to and from SharedPreferences trouble

我在尝试将 LocalDate 存储在 SharedPreferences 中时遇到了一个问题 运行。使用 Gson 库,我将 Task.java(自定义 class)实例列表转换为字符串并将其写入 SharedPreferences。 Task 实例包含一个 LocalDate 变量。检索该 LocalDate 变量时,它总是 returns 空字符串或日期设置为 0000-00-00。

当只写入和读取 LocalDate 进行测试时,我 运行 遇到了同样的问题。

这是试用代码:

LocalDate testDate = LocalDate.now();
System.out.println("TestDate before: " + testDate);

SharedPreferences.Editor editor = pref.edit();
Gson gson = new Gson();
editor.putString("testdate", gson.toJson(testDate));

System.out.println("TestDate String after: " + pref.getString("testdate", null));

LocalDate newtestDate = gson.fromJson(pref.getString("testdate", null), new TypeToken<LocalDate>(){}.getType());

System.out.println("TestDate as Date after: " + newtestDate);
       

我得到的输出:

I/System.out: TestDate before: 2021-03-27
I/System.out: TestDate String after: {}
I/System.out: TestDate as Date after: 0000-00-00

您需要 commit()apply() 您的 SharedPreferences.Editor 更改才能使它们实际出现在 SharedPreferences 中以供阅读。

另外,开箱即用的gson不知道如何序列化LocalDates。为此,您需要自定义 TypeAdapter。参见

补充一下 @lato 的精彩答案,SharedPreferences.Editor 的 commit()apply() 在用例上存在重大差异。

commit() 是同步的,它 return 是一个布尔值,表示成功或失败。

apply() 是异步的,速度更快,而且 return 什么都没有。该函数是在 2.3 中添加的,作为对 commit() 的改进,因此是更高效代码的选择。