I'm running into an issue when trying to store a LocalDate
in SharedPreferences
. Using the Gson library I turn a list of Task.java
(custom class) instances into a string and write it to SharedPreferences. The Task instances contain a LocalDate variable. When retrieving that LocalDate variable, it always returns an empty string or date set to 0000-00-00.
When writing & reading only a LocalDate for testing I run into the same problem.
This is the code for trying it out:
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);
Output I get:
I/System.out: TestDate before: 2021-03-27
I/System.out: TestDate String after: {}
I/System.out: TestDate as Date after: 0000-00-00