How to save List Of HashMap in android?
I have a hashmap of string
HashMap<String, String> hashMap = new HashMap<>();
hashMap.put("name", name);
hashMap.put("number", number);
hashMap.put("profileImage", image);
and a List of Hashmap
List<HashMap<String, String>> recents = new ArrayList<>();
recents.add(hashMap);
Now I have to save this list
I have tried using https://github.com/pilgr/Paper to save this List
Paper.book().write("recents", recents);
but i can't get the list back
List<HashMap<String, String>> list = Paper.book().read("recents");
HashMap<String,String> hashMap = list.get(0);
String name = hashMap.get("name");
String number = hashMap.get("number");
String image = hashMap.get("profileImage");
Uses of the code
actually I'm passing this list to recycelerViewAdapeter and from there in OnBindViewHolder() I'm getting all the Hashmap values and displaying it to user
Saving Data Code
Paper.init(this);
List<HashMap<String, String>> recents = new ArrayList<>();
HashMap<String, String> hashMap = new HashMap<>();
hashMap.put("name", name);
hashMap.put("number", number);
hashMap.put("profileImage", image);
recents.add(hashMap);
Paper.book().write("recents", contacts);
Receiving Data Code
Paper.init(requireActivity());
recyclerView = view.findViewById(R.id.recyclerView);
List<HashMap<String, String>> list = Paper.book().read("recents");
Adapter = new Adapter(requireActivity(), list);
recyclerView.setAdapter(Adapter);
You can use Gson and SharedPreferences to do the same.
implementation 'com.google.code.gson:gson:2.8.9'
Example:
private SharedPreferences sp;
private HashMap<String, Boolean> favs;
....
....
public void addFavourite(String wall_name) {
favs = getFavourites();
favs.put(wall_name, true);
setFavourties();
}
public void removeFav(String wall_name) {
favs = getFavourites();
favs.put(wall_name, false);
setFavourties();
}
private void setFavourties() {
SharedPreferences.Editor pe = sp.edit();
Gson gson = new Gson();
String j = gson.toJson(favs);
pe.putString("Favourites", j);
pe.apply();
}
public HashMap<String, Boolean> getFavourites() {
Gson gson = new Gson();
String j = sp.getString("Favourites", null);
if (j != null) {
Type stringBooleanMap = new TypeToken<HashMap<String, Boolean>>() {
}.getType();
return gson.fromJson(j, stringBooleanMap);
} else {
return new HashMap<>();
}
}