Reputation:
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
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
<T>
in method define a generic type TUpvotes: 2
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