ArrayList <HashMap <String, String >> cannot be properly converted to JSONArray for API9

I am having a problem saving mine ArrayList

in my general settings. I decided to convert ArrayList<HashMap<String, String>>

to JSONArray

so that I can parse the JSON next time I need it as I cannot save the ArrayList> as a string and return it to its original form.

Now it happens ArrayList

to convert successfully to JSON for my device running in API 19, but strangely it doesn't convert correctly for my emulator device running in API 9. When I check the reason, it happens because the converted string is not formatted correctly. which results in an error. Not properly formatted, I mean that instead of formatting, [{"key":"value"}]

it gets converted to [{key:value}]

where double quotes are stripped, which is what the JSON requires causing this error message:

org.json.JSONException: Unterminated object at character

      

Here's the code:

private void storeStatusInSharedPreference(ArrayList<HashMap<String, String>> items){
    SharedPreferences my_prefs = getActivity().getSharedPreferences("my_prefs", getActivity().MODE_PRIVATE);

    JSONArray result = new JSONArray(items);
    my_prefs.edit().putString("test", result.toString()).apply();

}

      

I'm not sure if the same thing will happen for other devices / versions, as I'm only testing those, so I didn't apply API version checking to handle it.

+3


source to share


1 answer


You seem to be keeping the list of arrays in your general privilege,

Sharedpreferences Lets you store String in a way that might help you



private void storeStatusInSharedPreference(ArrayList<HashMap<String, String>> items){
    SharedPreferences my_prefs = getActivity().getSharedPreferences("my_prefs", getActivity().MODE_PRIVATE);

    //JSONArray result = new JSONArray(items);
    my_prefs.edit().putString("test", items.toString()).commit();
}

      

This will work fine.

0


source







All Articles