Tuesday, 27 August 2013

JSONArray Data Storage

JSONArray Data Storage

What I am trying to achieve:
I want to create a data store inside an application that would override
itself onto a JSONArray and for that purpose I am using the following
method:
Code:
public void insertdata_checkbox(String key, String value){
String jsonstring = pref.getString(KEY_JSONVALUE, null);
try{
JSONObject jsob = new JSONObject(jsonstring);
if(!jsob.isNull(key)){
JSONArray jsonarr = jsob.getJSONArray(key);
if(!Arrays.asList(jsonarr).contains(value)){
jsonarr.put(value);
jsob.remove(key);
jsob.put(key, value);
}
}else{
JSONArray jsonarr = new JSONArray();
jsonarr.put(value);
jsob.put(key, jsonarr);
}
jsonstring = jsob.toString();
}catch(JSONException e){
e.printStackTrace();
}
Log.i("CHECKBOXES", jsonstring);
editor.putString(KEY_JSONVALUE,jsonstring);
editor.commit();
}
Where :
SharedPreferences pref;
Editor editor;
Suppose if I have a JSON response like this:
{ "abc": "xyz" , "array" :["aa", "bb", "cc"], "abc":"xyz" }
Through this function I would like to access the **array object** and get
into its JSONArray and insert the following "aa", "bb" and "cc" values
myself.
But for some reason the following code inserts only the latest value to
it, omitting the values that were put in later. For e.g. if I were to
insert the values in the following order:
1. aa
2. bb
3. cc
Only cc would be stored inside the array and strangely enough the array's
JSONArray is destroyed. outputting the following :
{ "abc": "xyz" , "array" : "cc", "abc":"xyz" }
The logcat also shows the following error:
08-27 21:31:53.370: W/System.err(2871): org.json.JSONException: Value
Surveys at measured_community of type java.lang.String cannot be converted
to JSONArray
08-27 21:31:53.371: W/System.err(2871): at
org.json.JSON.typeMismatch(JSON.java:100)
08-27 21:31:53.371: W/System.err(2871): at
org.json.JSONObject.getJSONArray(JSONObject.java:548)
08-27 21:31:53.371: W/System.err(2871): at
com.ia.developmentcheck.controller.SharePrefFormonitoring.insertdata_checkbox(SharePrefFormonitoring.java:90)
where line 90 is
JSONArray jsonarr = jsob.getJSONArray(key);
of the following code mentioned above.
Can someone please help me insert values on to this JSONArray without
disrupting its structure.

No comments:

Post a Comment