org.json.JSONObject cannot be converted to JSONArray in android org.json.JSONObject cannot be converted to JSONArray in android json json

org.json.JSONObject cannot be converted to JSONArray in android


You could try this:

JSONObject object = new JSONObject(result);JSONArray Jarray  = object.getJSONArray("contacts");for (int i = 0; i < Jarray.length(); i++) {   JSONObject Jasonobject = Jarray.getJSONObject(i);}


The url (http://api.androidhive.info/contacts/) returns a JSON object and not a JSON array...

Here:

JSONArray Jarray = new JSONArray(result);    for (int i = 0; i < Jarray.length(); i++) {        JSONObject Jasonobject = null;

You are assuming the result is a json array. If you do it like the following it will work:

JSONObject Jasonobject = new JSONObject(result);JSONArray Jarray = Jasonobject.getJSONArray("contacts");for (int i = 0; i < Jarray.length(); i++) { ...}


try using this

JSONObject Jarray = new JSONObject(result);

instead of

JSONArray Jarray = new JSONArray(result);

and next

JSONArray Jarray = Jasonobject.getJSONArray("contacts");

and the for loop continues

Download image from URL

Pass the URL to this particular method and you can download the image to the gridview

private void downloadImage(String urlStr) {    final String url = urlStr;            InputStream in = null;            Message msg = Message.obtain();            msg.what = 1;            try {                in = openHttpConnection(url);                bitmap = BitmapFactory.decodeStream(in);                Bundle b = new Bundle();                b.putParcelable("bitmap", bitmap);                msg.setData(b);                in.close();            } catch (Exception e1) {                e1.printStackTrace();            }           }private InputStream openHttpConnection(String urlStr) {    InputStream in = null;    int resCode = -1;    try {        URL url = new URL(urlStr);        URLConnection urlConn = url.openConnection();        if (!(urlConn instanceof HttpURLConnection)) {            throw new IOException ("URL is not an Http URL");        }        HttpURLConnection httpConn = (HttpURLConnection)urlConn;        httpConn.setAllowUserInteraction(false);        httpConn.setInstanceFollowRedirects(true);        httpConn.setRequestMethod("GET");        httpConn.connect();        resCode = httpConn.getResponseCode();                        if (resCode == HttpURLConnection.HTTP_OK) {            in = httpConn.getInputStream();                                        }            } catch (MalformedURLException e) {        e.printStackTrace();    } catch (IOException e) {        e.printStackTrace();    }    return in;}