0

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
tschoele
  • 3
  • 2

2 Answers2

3

You need to commit() or apply() your SharedPreferences.Editor changes for them to actually be there in the SharedPreferences for reading.

In addition, gson out of the box does not know how to serialize LocalDates. You need a custom TypeAdapter for that. See Serialize Java 8 LocalDate as yyyy-mm-dd with Gson

laalto
  • 150,114
  • 66
  • 286
  • 303
  • Thanks for the quick answer, I don't how I missed that in the testing code. Sadly I do `commit()` in the actual code for the app, so there seems to be an additional problem. I added commit() to the test code and now the return is still empty (seems reset)```I/System.out: TestDate before: 2021-03-27 I/System.out: TestDate String after: {} I/System.out: TestDate as Date after: 0000-00-00``` – tschoele Mar 27 '21 at 14:48
  • Oh ok so if I have an instance of some class that contains a LocalDate, I can't serialize that instance without "loosing" the LocalDate value in it? Do I have to take the LocalDate Variable out and serialize it on its own? – tschoele Mar 27 '21 at 15:09
0

Just to add to @lato's awesome answer, there is a major difference in use-case between SharedPreferences.Editor's commit() and apply().

commit() is synchronous and it returns a boolean which indicates success or failure.

apply() is asynchronous, faster and it doesn't return anything. The function was added in 2.3 as an improvement over commit() and is thus, the option of choice for more efficient code.

Taslim Oseni
  • 6,086
  • 10
  • 44
  • 69