【问题标题】:how to restore my saved data hashMap<String, ArrayList<List>>如何恢复我保存的数据 hashMap<String, ArrayList<List>>
【发布时间】:2020-08-14 16:30:33
【问题描述】:

我需要在关闭应用程序时恢复我保存的数据,但我不知道如何..

这是保存方法:

public void saveHashMap(HashMap<String, ArrayList<List>> map) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    Gson gson = new Gson();
    for (Map.Entry<String, ArrayList<List>> entry : map.entrySet()) {
        String json = gson.toJson(entry.getValue());
        Log.i(TAG, "SAVED KEY = " + entry.getKey() + " value "+ json);
        prefs.edit().putString(entry.getKey(), json);

    }
}

理论上我认为保存方法有效,但我不知道如何制作恢复方法...

我需要恢复一个HashMap,可以吗?

【问题讨论】:

  • "prefs.edit().putString(entry.getKey(), json);" -> 你需要调用 apply() 或 commit() 否则值不会从编辑器保存到 SharedPreferences 文件...

标签: android arraylist hashmap


【解决方案1】:

您可以创建类似:restoreData() 的方法并使用 SharedPreferences 中保存的数据来恢复它。

查看链接:https://developer.android.com/reference/android/content/SharedPreferences#getAll()

【讨论】:

    【解决方案2】:

    看起来您试图将 ArrayList 存储为首选项,因为您将其转换为字符串值,然后存储相同的值。

    首先,您需要维护一个键,以便您可以获取其对应的值。 在这种情况下,您需要维护一个键数组。 那么,

    第 1 步: 从首选项中获取字符串,

    String json = pref.edit().getString(entry.getKey());

    然后第 2 步:将您的值字符串转换为原始对象形式。

    ArrayList yourValue = gson.fromJson(json, new TypeToken(){}.getType());

    试一试,我不确定它是否可以调试代码。但是 TypeToken 是一种使用运行时解析的方式。您可以考虑这种方式以获得所需的解决方案

    祝你好运!

    【讨论】:

    • 欢迎,如果您找到有用的答案。你可以接受它。
    猜你喜欢
    • 2013-10-04
    • 2013-05-12
    • 1970-01-01
    • 2012-06-18
    • 2016-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多