Search code examples
javagenericsandroid-sharedpreferencesandroidgson

save generic type of List in SharedPreference


I want to make a generic method for saving any type of List to SharedPreference.

public static List<T extends Object> readAnyTypeOfList<T>() {
        Gson gson = new Gson();
        return (gson.fromJson(SharedPref.read("anyTypeOfList", "[]"),
                new TypeToken<List<T>>() {
                }.getType()));
    }

And for saving any Type of List

public static void saveAnyTypeOfList(List<T> value) {
    Gson gson = new GsonBuilder().create();
    JsonArray jsonArray = gson.toJsonTree(value).getAsJsonArray();
    SharedPref.save("anyTypeOfList", jsonArray.toString());
}

but both methdos give error . what is the proper way to create a generic method. I have also tried this

where working example is

    public static ListOfModel = "ListKey"

    public static List<ModelClass> readListOfModel() {
        Gson gson = new Gson();
        return (gson.fromJson(SharedPref.read(ListOfModel, "[]"),
                new TypeToken<List<ModelClass>>() {
                }.getType()));
    }

    public static void saveListOfModel(List<ModelClass> value) {
        Gson gson = new GsonBuilder().create();
        JsonArray jsonArray = gson.toJsonTree(value).getAsJsonArray();
        SharedPref.save(ListOfModel, jsonArray.toString());
    }

Solution

  • You can not create a TypeToken generically like that. T is erased, the specific type information is not available at runtime, so there will be no information in the token.

    The error you made in the declaration of the generic methods, is that you never declared the type variable T. Like this:

    public static <T> someMethod(T t) {...}
    //............^^^
    

    (The syntax is different from C#)

    My advice would be to do like this:

    public static <T> void saveAnyTypeOfList(String key, List<T> value) {
        Gson gson = new GsonBuilder().create();
        JsonArray jsonArray = gson.toJsonTree(value).getAsJsonArray();
        SharedPref.save(key, jsonArray.toString());
    }
    
    public static <T> List<T> readAnyTypeOfList(String key, TypeToken<List<T>> tt) {
        Gson gson = new Gson();
        return (gson.fromJson(SharedPref.read(key, "[]"), tt.getType()));
    }