Jacky
Jacky

Reputation: 298

Retrieve hashmap data SharedPreferences

I used HashMap to store data which I received using API. After that, I used SharedPreferences to store the received HashMap data. Storing part is done. I can see the number of records which I wanted to store using SharedPreferences.

Here is the code to save data:

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

After the above steps, I followed this set of code to set and get the value from SharePreferences, which I stored in application using SharedPreferences. For that, I used this below code:

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

Now, I am trying to retrieve the data which I stored in SharedPreferences. Here is the code I used to retrieve the data:

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

When I debug the app, I get values in Labels below format. The same number of records I received.

The format goes like this:

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

How can I get the each data from this format?

Upvotes: 0

Views: 612

Answers (5)

Sharath kumar
Sharath kumar

Reputation: 4132

Instead convert the map to gson String and store it in preference like this

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

Upvotes: 2

Steve.P
Steve.P

Reputation: 54

SharedPreference doesn't support store map object. https://developer.android.com/reference/android/content/SharedPreferences.Editor.html. So your code just store data obj.toString, that why you see result in debug. If you want to store a map, you can store as json and use put string.

Upvotes: 0

Mohit Mathur
Mohit Mathur

Reputation: 36

You should cast lables string into hashmap object This is one solution. If you want to make it more generic, you can us StringUtils library.

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
}

For example, you can switch

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

to

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

and after that

You should cast value in LabelModel like

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

Upvotes: 1

ישו אוהב אותך
ישו אוהב אותך

Reputation: 29794

There is no support for HashMap in SharedPreferences. So, you can't save the HashMap by converting it to a string directly, but you can convert it to JSON string. You can use google-gson in this case. Something like this:

First, include the dependency:

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

Saving from HashMap object to preference:

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

Get HashMap object from preference:

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

Upvotes: 2

Abu Yousuf
Abu Yousuf

Reputation: 6107

You are getting {572=com.*****.landlord.model.LabelModel@23a282e, 598=com.*****.landlord.model.LabelModel@c954fcf, 590=com.*****.landlord.model.LabelModel@2fe3d5c, 103=com.*****..........} this because Object default toString() method use hashcode.

Storing complex object in SharedPreference is not recommended. SharedPreference don't support HashMap link.

For storing simple object you have to convert the object into String using toString() method. You can use Gson for converting object to String and that will be a easy solution.

You can also use ObjectOutputStream to write it to the internal memory check this link

Upvotes: 1

Related Questions