简体   繁体   English

如何在 android 中保存 HashMap 的列表?

[英]How to save List Of HashMap in android?

I have a hashmap of string我有一个字符串 hashmap

HashMap<String, String> hashMap = new HashMap<>();
hashMap.put("name", name);
hashMap.put("number", number);
hashMap.put("profileImage", image);

and a List of Hashmap和 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我尝试使用https://github.com/pilgr/Paper来保存此列表

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实际上我正在将此列表传递给 recyclerViewAdapeter 并从那里在 OnBindViewHolder() 中获取所有 Hashmap 值并将其显示给用户

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.您可以使用 Gson 和 SharedPreferences 来做同样的事情。

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<>();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM