Artem
Artem

Reputation: 4639

Cannot read List with Gson afer writing

I want to save and read List<MyObj> to sharedPreferences using Gson.

This is my write method:

private static final String GAS_STATIONS_LIST_KEY = "gasStationsListKey";

@Override
public void save(@NonNull List<MyObj> gasStations) {
    saveStr(GAS_STATIONS_LIST_KEY, gson.toJson(gasStations));
}

 private void saveStr(@NonNull String key, @Nullable String value) {
        sharedPreferences
                .edit()
                .putString(key, value)
                .apply();
    }

And this is my read method:

@Override
public List<MyObj> getGasStationList() {
    final Type type = new TypeToken<List<MyObj>>() {
    }.getClass();
    final List<MyObj> gasStations = gson.fromJson(GAS_STATIONS_LIST_KEY, type); // here null
    if (gasStations != null && !gasStations.isEmpty()) {
        return gasStations;
    } else {
        return new ArrayList<>();
    }
}

But when I try read data I get null (comment in last code part).

How to fix it?

Upvotes: 1

Views: 40

Answers (2)

Mohamed AbdelraZek
Mohamed AbdelraZek

Reputation: 2819

SharedPreferences only store primitive data Types.

Upvotes: 1

Devrim
Devrim

Reputation: 15533

You are not getting the saved json content from shared prefences. You are trying to deserialize the key to a list, not the json content which is saved with that key.

Change this:

final List<MyObj> gasStations = gson.fromJson(GAS_STATIONS_LIST_KEY, type);

To this:

String savedJsonContent =  sharedPreferences.getString(GAS_STATIONS_LIST_KEY, null);
final List<MyObj> gasStations = gson.fromJson(savedJsonContent , type);

Upvotes: 1

Related Questions