【问题标题】:How to save List Of HashMap in android?如何在android中保存HashMap列表?
【发布时间】:2022-01-22 06:32:47
【问题描述】:

我有一个字符串的哈希图

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

和一个Hashmap列表

List<HashMap<String, String>> recents = new ArrayList<>();
recents.add(hashMap);

现在我必须保存这个列表

我已尝试使用https://github.com/pilgr/Paper 来保存此列表

Paper.book().write("recents", recents);

但我无法取回列表

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");

代码的使用

实际上我将此列表传递给 recycelerViewAdapeter 并从那里在 OnBindViewHolder() 中获取所有 Hashmap 值并将其显示给用户

保存数据代码

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

接收数据代码

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

【问题讨论】:

  • 我能够从您的代码中保存和检索信息。那你能详细说明一下这个问题吗?你有任何错误吗?你得到一个空列表吗?还是别的什么?
  • 抱歉,这个列表返回给我一个空列表,在 hashmap 中有空值
  • 好的。那么你能告诉我你从哪里得到变量name, number等吗?...在​​保存期间。你能把代码贴出来吗?如果可能,您可以发布完整的相关课程代码吗?我想首先确保它们不为空。
  • 你能发布与Paper.book().write相关的完整代码吗?我想看看你写的对不对。

标签: java android list hashmap save


【解决方案1】:

您可以使用 Gson 和 SharedPreferences 来做同样的事情。

implementation 'com.google.code.gson:gson:2.8.9'

例子:

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

【讨论】:

    猜你喜欢
    • 2017-05-14
    • 2021-06-24
    • 2016-06-23
    • 2016-06-15
    • 1970-01-01
    • 2012-03-02
    • 2013-05-07
    • 2019-06-04
    • 1970-01-01
    相关资源
    最近更新 更多