1

I know this is a very commonly asked question and I found quite a lotta posts in SO. My code is as below and I don't see a reason why the json array is returning null. Could someone please review it for me please? I've left no stones left unturned! :(

JsonArray jsonArr = JSONfunctions.getJSONfromURL(url);
    try {
        if (jsonArr != null) {
            for (int i = 0; i < jsonArr.length(); i++) {
                HashMap<String, String> map = new HashMap<String, String>();
                JSONObject jsonObj = jsonArr.getJSONObject(i);

                map.put(TAG_CODE, jsonObj.getString("Code"));
                map.put(TAG_DISPLAY_NAME, jsonObj.getString("UserName"));
                map.put(TAG_PROGRAM_NAME, jsonObj.getString("Password"));
                mylist.add(map);
            }
        }
    } catch (JSONException e) {
        Log.e("log_tag", "Error parsing data " + e.toString());
    }                                                                                      






public class JSONfunctions {

public static JSONArray getJSONfromURL(String url) {
    InputStream is = null;
    String result = "";
    JSONArray jArray = null;

    // http post
    try {

        HttpClient httpclient = new DefaultHttpClient();
        HttpGet httppost = new HttpGet(url);
        // httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();

    } catch (Exception e) {
        Log.e("log_tag", "Error in http connection " + e.toString());
    }

    // convert response to string
    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        result = sb.toString();

                // Result is always returning me an array.(not null)

    } catch (Exception e) {
        Log.e("log_tag", "Error converting result " + result);
    }
    try {
        jArray = new JSONArray(result);

                // Goes into the catch block

    } catch (JSONException e) {
        // TODO Auto-generated catch block
        Log.e("log_tag", "Error parsing result " + result);
    }
    return jArray;

}

}

buggydroid
  • 1,870
  • 6
  • 25
  • 36
  • Where do you kept this code, are using separate thread or AsyncTask? – Pragnani May 11 '13 at 11:52
  • In a separate class file but not in Aysnc Task. It seem to be working sometime back. :( – buggydroid May 11 '13 at 11:53
  • It will work on older android version (pre 3.0). You must move it in an AsyncTask – Blackbelt May 11 '13 at 11:54
  • 1
    What is the error message? I mean when it goes to the catch block. – Saeid Farivar May 11 '13 at 11:55
  • log_tag: Error parsing result {"FirstName": "\"firstname"", "LastName": "\"lastname\"", "Code": "\"id\""}. So result seems fine. jArray = new JSONArray(result); is the problem. @blackbelt - I've done this quite a few times but works fine without an Async task but will give that a shot as well. Thanks. – buggydroid May 11 '13 at 12:05
  • 1
    what the server is returning is not a JSONArray but a JSONOBject. you should change the type of jArray from JSONArray to JSONObject – Blackbelt May 11 '13 at 12:15
  • @blackbelt Post this as an answer, because that's what obviously is the problem here (as everybody should be able to see from the Exception message or by debugging and looking the variables values!) – Ridcully May 11 '13 at 12:22
  • Since it's an unnamed array. It can be directly returned and used as an Array. There is no need to return a JsonObject. http://stackoverflow.com/questions/6751681/problem-in-parsing-json-in-android http://stackoverflow.com/questions/10164741/get-jsonarray-without-array-name – buggydroid May 11 '13 at 12:24
  • @SowmyaGuru I disagree. An JSONArray has to start with [] – Blackbelt May 11 '13 at 12:25

1 Answers1

1

What the server is returning ( {"FirstName": "\"firstname"", "LastName": "\"lastname\"", "Code": "\"id\""} ) is a JSONObject and not a JSONArray, you should change

JSONArray jArray = null;

in

JSONOBject jArray = null;

and

jArray = new JSONArray(result);

in

jArray = new JSONOBject (result);
Blackbelt
  • 156,034
  • 29
  • 297
  • 305
  • JSONObject json = JSONfunctions.getJSONfromURL(url); JSONArray jsonArr= json.getJSONArray(TAG); What do you suggest to handle the unnamed arrays where the tag is absent? Also it's a JsonArray cuz the the tags are absent. Hence I can use getJsonFromUrl directly. – buggydroid May 11 '13 at 12:48
  • you do not have a jsonarray. You have a jsonobject. – Blackbelt May 11 '13 at 12:51
  • Alright! So the next question is how do I handle the JSONobject in case of unnamed arrays? This is the only way I could find to do it. And it has worked before. Do you have a sample to handle unnamed arrays using JSONObject? – buggydroid May 11 '13 at 12:53
  • I tried without returning the JSONobject and pushed the values into a hashmap immediately after I get the object and it worked. – buggydroid May 12 '13 at 12:51