0

I am trying to fetch Data from MySql Database to a list view. I am getting one exception JSONArray cannot be converted to JSONObject. Please help me I am new in Android. How I can convert JASONArray to JASONObject. Please help me.

08-19 09:44:43.640: E/JSON(895): {"STATUS":"1","user_id":"92","role":"Clamper","area":"Uptown","street":"Tom Mboya"}
08-19 09:44:44.980: I/Choreographer(895): Skipped 109 frames!  The application may be doing too much work on its main thread.
08-19 09:44:48.200: E/JSON(895): [{"car_no":"MP04","fine_id":"51769","area":"Uptown","street":"Tom Mboya"},{"car_no":"MP09878","fine_id":"51768","area":"Uptown","street":"Tom Mboya"},{"car_no":"MP071256","fine_id":"51767","area":"Uptown","street":"Tom Mboya"},{"car_no":"MP07123","fine_id":"51766","area":"Uptown","street":"Tom Mboya"}]
08-19 09:44:48.530: E/JSON Parser(895): Error parsing data org.json.JSONException:     Value 
[
{"fine_id":"51769"
,"street":"Tom Mboya"
,"area":"Uptown"
,"car_no":"MP04"
},
{"fine_id":"51768"
,"street":"Tom Mboya"
,"area":"Uptown"
,"car_no":"MP09878"
},{"fine_id":"51767","street":"Tom Mboya","area":"Uptown","car_no":"MP071256"}, {"fine_id":"51766","street":"Tom Mboya","area":"Uptown","car_no":"MP07123"}
]
 of type org.json.JSONArray cannot be converted to JSONObject
08-19 09:44:48.530: D/Fetching Response(895): {"role":"Clamper","user_id":"92","area":"Uptown","STATUS":"1","street":"Tom Mboya"}

here my activity code is

public class ClamperActivity extends Activity {

 private ProgressDialog pDialog;
 private ListView list;
 private int success;
 JSONParser jsonParser = new JSONParser();

 public static String user_id="";

 static String url= "http://192.168.1.13/testkrcs/main/get_clamped";

 // JSON Node names
 private static final String TAG_SUCCESS = "success";

  private void minimizeApp()
  {
    Intent localIntent = new Intent("android.intent.action.MAIN");
    localIntent.addCategory("android.intent.category.HOME");
    localIntent.setFlags(268435456);
    startActivity(localIntent);
  }

  public void onBackPressed()
  {
    minimizeApp();
  }

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_clamper);

    list = (ListView)findViewById(R.id.list);
    new FetchVehiclesTask().execute();

}

class FetchVehiclesTask extends AsyncTask<String, String, String>
{
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(ClamperActivity.this);
        pDialog.setMessage("Fetching Vehicles List...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    protected String doInBackground(String... args)
    {
        List<NameValuePair> params = new ArrayList<NameValuePair>();
           params.add(new BasicNameValuePair("street",LoginActivity.street));
           params.add(new BasicNameValuePair("area",LoginActivity.area));
           params.add(new BasicNameValuePair("user_id",LoginActivity.user_id));

            JSONObject json = jsonParser.getJSONFromUrl(url, params);

            Log.d("Fetching Response", json.toString());

               return null;
    }
    protected void onPostExecute(String file_url) {
        // dismiss the dialog once done
        pDialog.dismiss();
    }
}

}

here is my JASONPArser class code

public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {

    // Making HTTP request
    try {
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(new UrlEncodedFormEntity(params));

        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    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();
        json = sb.toString();
        Log.e("JSON", json);
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);            
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jObj;

}
4
  • jsonParser.getJSONFromUrl(url, params); returns json which is a json array not a JSONObject Commented Aug 19, 2014 at 14:17
  • @Raghunandan can u please provide me the solution Commented Aug 19, 2014 at 14:18
  • post your json also the one you want to parse. i see many of them in the logcat posted Commented Aug 19, 2014 at 14:19
  • @Raghunandan I already post json Sir Commented Aug 19, 2014 at 14:24

2 Answers 2

2

Your JSONArray is an array of JSONObject; you should access the elements in your array (loop on your JSONArray) to get your JSONObjects.

I would something like this:

JSONArray jsonA = jsonParser.getJSONFromUrl(url, params);

if (jsonA!=null){
    for (int i=0;i<jsonA.length();i++){
        JSONObject json=jsonA.getJSONObject(i);
       // Deal with each of your JSONObject
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

I think I have to make changes in JasonParser class also
Try changing every JSONObject references in your method to JSONArray (this also means the object returned by your method).
1

It means you have to change your code to a JSON array to match the data:

Create a new function:

getJSONStringFromUrl

public String getJSONStringFromUrl(String url, List<NameValuePair> params) {
 String json = null;
    // Making HTTP request
    try {
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(new UrlEncodedFormEntity(params));

        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    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();
        json = sb.toString();
        Log.e("JSON", json);
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // return JSON String
    return json;

}

doInBackground

protected String doInBackground(String... args)
{
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("street",LoginActivity.street));
    params.add(new BasicNameValuePair("area",LoginActivity.area));
    params.add(new BasicNameValuePair("user_id",LoginActivity.user_id));
    try {
        String jsonString = jsonParser.getJSONStringFromUrl(url, params);
        JSONObject jsonObj = new JSONObject(jsonString);
        Log.d("Fetching Response", jsonObj.toString());

        String userId jsonObj.getString("user_id");
        Log.d("mylog", "userId = " + userId);      
    } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

}

9 Comments

again its give an error at return json and the error is Type mismatch: cannot convert from String to JSONObject
@HarshitAgarwal the method return type change public String getJSONStringFromUrl the name also
that error has resolve now i get another error at JSONObject jsonObj = jsonArray.get(i); and the error is Type mismatch: cannot convert from Object to JSONObject
Hey please help me to fix it this one error also please I request you
@HarshitAgarwal what are you getting for Log.d("Fetching Response", jsonArray.toString());
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.