简体   繁体   中英

Not able to retrieve hashmap from sharedPreferences

I am retrieving list of ParseObject from Parse and casting into list of HashMap,then converting it to JSONArray and storing in SharedPrefrences as String

List<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>();
                    for (int i = 0; i < list.size(); i++) {
                        ParseObject foundObject = list.get(i);
                        HashMap<String, Object> industry = new HashMap<String, Object>();
                        industry.put("CategoryName", foundObject.get("category"));
                        industry.put("lastUpdated", new Date());
                        industry.put("Jobs", foundObject.getList("jobs"));
                        data.add(industry);
                    }
                        JSONArray result = new JSONArray(data);
                        editor.putString("Categories", result.toString());
                        editor.commit();

Then i am retrieving from locally saved String(JSONArray)

String storedCollection = pref.getString("Categories", null);
        //Parse the string to populate your collection.
        collection = new ArrayList<HashMap<String, Object>>();
        if (storedCollection != null) {
            try {
                JSONArray array = new JSONArray(storedCollection);

                HashMap<String, Object> item = null;
                for (int i = 0; i < array.length(); i++) {
                    try {

                        JSONObject obj = new JSONObject((String) array.get(i));


                        Iterator<String> it = obj.keys();

                        item = new HashMap<String, Object>();
                        while (it.hasNext()) {
                            String key = it.next();
                            item.put(key, obj.get(key));
                        }
                        if (item == null) {
                            JSONObject obj2 = (JSONObject) array.get(i);
                            Iterator<String> it1 = obj2.keys();
                            item = new HashMap<String, Object>();
                            while (it1.hasNext()) {
                                String key = it.next();
                                item.put(key, obj2.get(key));
                            }
                        }
                    } catch (JSONException e) {

                    }
                    collection.add(item);
                }

            } catch (JSONException e) {
                Log.e("JSON", "while parsing", e);
            }
        }

Which works fine on and above lollipop version but giving error on lower versions

org.json.JSONException: Unterminated array at character 21 of {jobs=[Bar management, Baker, Bar service, Barista, Car park services, Chef, Cleaning services, Cooking & food preparation], lastUpdated=Tue Jun 28 10:22:03 GMT+05:30 2016, category=fulltime}

and sometimes getting this error

java.lang.ClassCastException: org.json.JSONObject cannot be cast to java.lang.String

The problem is the array that you store is JSONArray of HashMaps. When you retrieve the array, the objects in the array are strings(representing HashMap). JSONObject obj = new JSONObject((String) array.get(i)); which you are trying to convert to JSONObject.This is the problem. Either you convert each of this string back to hashmap or you can use JSONObject in place of HashMap like this to store the data

public void storeInPrefs(){
    JSONArray data = new JSONArray();
    for (int i = 0; i < list.size(); i++) {

        JSONObject industry = new JSONObject();
        ParseObject foundObject = list.get(i);
        try {
            industry.put("CategoryName", foundObject.get("category"));
            industry.put("lastUpdated", new Date());
            industry.put("Jobs", foundObject.getList("jobs"));
            data.put(industry);
        }
        catch (JSONException e) {
            e.printStackTrace();
        }
    }
    SharedPreferences preferences = this.getPreferences(MODE_PRIVATE);
    SharedPreferences.Editor editor = preferences.edit();
    editor.putString("Categories", data.toString());
    editor.commit();
}

And to parse the stored data and put it in collection, you can do this

public void parseStoredData(){
    SharedPreferences pref = this.getPreferences(MODE_PRIVATE);
    String storedCollection = pref.getString("Categories", null);
    //Parse the string to populate your collection.
    ArrayList<HashMap<String, Object>> collection = new ArrayList<HashMap<String, Object>>();
    if (storedCollection != null) {
        try {

            JSONArray array = new JSONArray(storedCollection);

            for (int i = 0; i < array.length(); i++) {
                try {

                    JSONObject object = array.getJSONObject(i);
                    HashMap<String,Object> item = new HashMap<String, Object>();
                    Iterator<String> it = object.keys();

                    while (it.hasNext()) {
                        String key = it.next();
                        item.put(key, object.get(key));
                    }

                    collection.add(item);
                } catch (JSONException e) {
                        e.printStackTrace();
                }

            }

        } catch (JSONException e) {
            Log.e("JSON", "while parsing", e);
        }
    }
}

In my opinion this would be easy for you.

try to use JSONObject object = new JSONObject(industry);

instead of JSONArray result = new JSONArray(data);

Thie object.toString() is like {"Jobs":["Bar management","Baker","Bar service"],"lastUpdated":"Tue Jun 28 13:54:24 GMT+08:00 2016","CategoryName":"fulltime"}

And the result.toString() is like [{"Jobs":["Bar management","Baker","Bar service"],"lastUpdated":"Tue Jun 28 13:54:24 GMT+08:00 2016","CategoryName":"fulltime"}]

I think the object is what you really want, and use JsonObject also when retrieving.

Hope helpful.

Addtionally, you can use this to verify your result.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM