gpt4 book ai didi

java - 检索 HashMap 数据 SharedPreferences

转载 作者:行者123 更新时间:2023-12-01 16:47:47 25 4
gpt4 key购买 nike

我使用HashMap来存储我使用API​​接收到的数据。之后,我使用SharedPreferences来存储接收到的HashMap数据。存储部分完成。我可以使用 SharedPreferences 查看要存储的记录数。

这是保存数据的代码:

if (result != null && result.length() > 0)
{
for (int j = 0; j < result.length(); j++)
{
JSONObject resultObj = result.getJSONObject(j);
String label_id = resultObj.getString("label_id");
String arabic = resultObj.getString("arabic");
String english = resultObj.getString("english");
String key = resultObj.getString("key");

//Create a new model and set the received value
LabelModel labelModel = new LabelModel();
labelModel.setLabelId(label_id);
labelModel.setArabic(arabic);
labelModel.setEnglish(english);
labelModel.setKey(key);

int label = Integer.parseInt(label_id);
//Put the value

map.put(label, labelModel);
}
}

//With the below line, I stored the hashMap data using SharedPreferences
Pref.setValue(mActivity, AppPrefrences.PREF_LABELS, map);

完成上述步骤后,我按照这组代码设置获取 SharePreferences 中的值,我使用 SharedPreferences 将其存储在应用程序中。为此,我使用了下面的代码:

public static String PREF_LABELS ="labels";

public static void setValue(@NonNull Context context, String key, Object obj) {
Pref.openPref(context);
Editor prefsPrivateEditor = Pref.sharedPreferences.edit();
prefsPrivateEditor.putString(key, String.valueOf(obj));
prefsPrivateEditor.commit();
prefsPrivateEditor = null;
Pref.sharedPreferences = null;
}

@Nullable
public static String getValue(@NonNull Context context, String key, Object obj) {
Pref.openPref(context);
String result = Pref.sharedPreferences.getString(key, String.valueOf(obj));
Pref.sharedPreferences = null;
return result;
}

现在,我正在尝试检索存储在 SharedPreferences 中的数据。这是我用来检索数据的代码:

String labels = Pref.getValue(mActivity, AppPrefrences.PREF_LABELS, "");

当我调试应用程序时,我得到以下格式的标签值。我收到的记录数量相同。

格式如下:

{572=com.*****.landlord.model.LabelModel@23a282e, 598=com.*****.landlord.model.LabelModel@c954fcf, 590=com.*****.landlord.model.LabelModel@2fe3d5c, 103=com.*****..........}

如何从这种格式中获取每个数据?

最佳答案

SharedPreferences 中不支持 HashMap。所以,你不能通过直接将HashMap转换为字符串来保存它,但你可以将其转换为JSON字符串。您可以使用google-gson在这种情况下。像这样的事情:

首先,包含依赖项:

compile 'com.google.code.gson:gson:2.8.2'

从 HashMap 对象保存到首选项:

Editor prefsEditor = mPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(map);
prefsEditor.putString("YourHashMap", json);
prefsEditor.commit();

从首选项中获取 HashMap 对象:

Gson gson = new Gson();
String json = mPrefs.getString("YourHashMap", "");
HashMap map = gson.fromJson(json, HashMap.class);

关于java - 检索 HashMap 数据 SharedPreferences,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46702042/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com