【问题标题】:Retrieve hashmap data SharedPreferences检索 hashmap 数据 SharedPreferences
【发布时间】:2017-10-12 05:27:04
【问题描述】:

我使用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, "");

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

格式如下:

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

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

【问题讨论】:

  • 在共享首选项中将 resultObj.toString() 存储为字符串而不是检索为字符串并解析是最佳实践!!

标签: java android sharedpreferences


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    而是将地图转换为 gson 字符串并像这样优先存储它

       //convert to string using gson
        Gson gson = new Gson();
        String mapString = gson.toJson(map);
    
        //save this in the shared prefs
        SharedPreferences prefs = getSharedPreferences("test", MODE_PRIVATE);
        prefs.edit().putString("yourkey", mapString).apply();
    
        //get from shared prefs in gson and convert to maps again
        String storedHashMapString = prefs.getString("yourkey",null);
        java.lang.reflect.Type type = new TypeToken<HashMap<String, String>>(){}.getType();
    
          //Get the hashMap
        HashMap<String, String> map = gson.fromJson(storedHashMapString, type);
    

    【讨论】:

      【解决方案3】:

      您得到{572=com.*****.landlord.model.LabelModel@23a282e, 598=com.*****.landlord.model.LabelModel@c954fcf, 590=com.*****.landlord.model.LabelModel@2fe3d5c, 103=com.*****..........} 这是因为对象默认toString() 方法使用hashcode

      不建议将复杂对象存储在 SharedPreference 中。 SharedPreference 不支持 HashMap link

      为了存储简单对象,您必须使用toString() 方法将对象转换为String。 您可以使用Gson 将对象转换为字符串,这将是一个简单的解决方案。

      您也可以使用ObjectOutputStream将其写入内存check this link

      【讨论】:

        【解决方案4】:

        您应该将标签字符串转换为 hashmap 对象这是一种解决方案。如果你想让它更通用,你可以使用 StringUtils 库。

        String value = "{first_name = mohit,last_name = mathur,gender = male}";
        value = value.substring(1, value.length()-1);           //remove curly brackets
        String[] keyValuePairs = value.split(",");              //split the string to creat key-value pairs
        Map<String,String> map = new HashMap<>();               
        
        for(String pair : keyValuePairs)                        //iterate over the pairs
        {
            String[] entry = pair.split("=");                   //split the pairs to get key and value 
            map.put(entry[0].trim(), entry[1].trim());          //add them to the hashmap and trim whitespaces
        }
        

        比如可以切换

        value = value.substring(1, value.length()-1);
        

        value = StringUtils.substringBetween(value, "{", "}");
        

        然后

        您应该在 LabelModel 中转换值 喜欢

        LabelModel labels = map.get("598");
        

        【讨论】:

          【解决方案5】:

          SharedPreference 不支持商店地图对象。 https://developer.android.com/reference/android/content/SharedPreferences.Editor.html。因此,您的代码只存储数据 obj.toString,这就是您看到调试结果的原因。如果要存储地图,可以存储为json并使用put string。

          【讨论】:

            猜你喜欢
            • 2016-10-30
            • 2013-08-10
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2020-06-05
            • 1970-01-01
            • 2017-12-17
            • 2013-03-08
            相关资源
            最近更新 更多