Skip to content Skip to sidebar Skip to footer

Android Jsonarray To Arraylist

I am trying to parse a JSONArray into and ArrayList in my android app. The PHP script correctly retuns the expected results, however the Java fails with a null pointer exception at

Solution 1:

try like this may help you,

publicvoidagencySearch(String tsearch)    {
        // Setting the URL for the Search by TownString url_search_agency = "http://www.infinitycodeservices.com/get_agency_by_city.php";
        // Building parameters for the searchList<NameValuePair> params = newArrayList<NameValuePair>();
        params.add(newBasicNameValuePair("City", tsearch));

        // Getting JSON string from URLJSONArray json = jParser.getJSONFromUrl(url_search_agency, params);

       ArrayList<HashMap<String, String>> resultsList = newArrayList<HashMap<String, String>>();

        for (int i = 0; i < json.length(); i++) {
            HashMap<String, String> map = newHashMap<String, String>();

            try {
                JSONObject c = json.getJSONObject(position);
                //Fill mapIterator<String> iter = c.keys();
                while(iter.hasNext())   {
                    String currentKey = it.next();
                    map.put(currentKey, c.getString(currentKey));
                }
                resultsList.add(map);

            }
            catch (JSONException e) {
                e.printStackTrace();

            }

        };

        MainActivity.setResultsList(resultsList);

    }

Solution 2:

Use custom method which convert your JSONArray to List instead of iterate and build List.

How to call :

try {
     ArrayList<HashMap<String,String>> list = (ArrayList<HashMap<String,String>>) toList(json);
} catch (JSONException e) {
     e.printStackTrace();
}

Convert json array to List :

private List toList(JSONArray array) throws JSONException {
    List list = new ArrayList();
    int size = array.length();
    for (int i = 0; i < size; i++) {
        list.add(fromJson(array.get(i)));
    }
    return list;
}

Convert json to Object :

privateObjectfromJson(Object json) throws JSONException {
    if (json == JSONObject.NULL) {
        returnnull;
    } elseif (json instanceofJSONObject) {
        returnjsonToMap((JSONObject) json);
    } elseif (json instanceofJSONArray) {
        returntoList((JSONArray) json);
    } else {
        return json;
    }
}

Convert json to map :

publicMap<String, String> jsonToMap(JSONObjectobject) throws JSONException {
    Map<String, String> map = newHashMap();
    Iterator keys = object.keys();
    while (keys.hasNext()) {
        String key = (String) keys.next();
        map.put(key, fromJson(object.get(key)).toString());
    }
    return map;
}

Post a Comment for "Android Jsonarray To Arraylist"