user10536091
user10536091

Reputation:

multiple types of array list via one method

How can I pass multiple types of array list via one method

Code

List<PostsModel> Posts = new ArrayList<>();
List<FavoriteModel> Favorite = new ArrayList<>();
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_posts);
        Posts = LoadArrayList("PostsList"); //Error here
        Favorite = LoadArrayList("FavoriteList"); //Error here
    }

public List<Object> LoadArrayList(String key) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    Gson gson = new Gson();
    String json = prefs.getString(key, null);
    Type type = new TypeToken<List<Object>>() {
    }.getType();
    return gson.fromJson(json, type);
}

I have tried a lot but don't work

Upvotes: 0

Views: 60

Answers (2)

Khemraj Sharma
Khemraj Sharma

Reputation: 58974

You can do it with Java Generics.

public <T> List<T> loadArrayList(String key) {
    //...
    Type type = new TypeToken<List<T>>() {
    }.getType();
    return gson.fromJson(json, type);
}

Now you can do

List<PostsModel> Posts = loadArrayList("PostsList");

Explanation

  • First <T> in method define a generic type T
  • Second T with return type defines the type of returning value.
  • You can use any name to variable T, like K, ListType. Usually developers use T for type.

Upvotes: 2

NIKHIL MAURYA
NIKHIL MAURYA

Reputation: 304

Change the function to

public <T> List<T> LoadArrayList(String key, Class<T> type) {
    SharedPreferences prefs = 
    PreferenceManager.getDefaultSharedPreferences(context);
    Gson gson = new Gson();
    return gson.fromJson(json, type);
}

Call it like

Posts = LoadArrayList("PostsList", PostsModel.class);

Upvotes: 1

Related Questions