1

I am currently learning how to create apps on Android Studio and have been trying to make a JSON connection with a server and bring back the information from the server and display it in my app. I have been able to make the connection as logical shows however I am unclear of the error that faces me and how to solve it. I will show here my two classes I have constructed to make the JSON connection and the error I am shown. When I run the emulator it just says, Unfotunatley, JSONconnection app has stopped working.

Thanks for the help

Error on logcat with exception

04-08 08:10:23.860    1656-1656/com.example.adam.jsonconnection E/JSON Parser﹕ Error parsing data org.json.JSONException: Value [{"id":"170656","RatingValue":"5","DistanceKM":"0.0483604565731744","PostCode":"M1 5QS","Latitude":"53.472442","BusinessName":"Cheeky Coffee Co","Longitude":"-2.240435","RatingDate":"2014-02-06","AddressLine1":"Unit 10, The Quadrangle","AddressLine2":"Chester Street","AddressLine3":"Manchester"},{"id":"171710","RatingValue":"3","DistanceKM":"0.0483604565731744","PostCode":"M1 5QS","Latitude":"53.472442","BusinessName":"Nando's","Longitude":"-2.240435","RatingDate":"2013-01-17","AddressLine1":"Unit 3, The Quadrangle","AddressLine2":"Chester Street","AddressLine3":"Manchester"},{"id":"172780","RatingValue":"4","DistanceKM":"0.0483604565731744","PostCode":"M1 5QS","Latitude":"53.472442","BusinessName":"Zouk Tea Bar & Grill","Longitude":"-2.240435","RatingDate":"2010-06-11","AddressLine1":"Unit 5 The Quadrangle","AddressLine2":"Chester Street","AddressLine3":"Manchester"},{"id":"170593","RatingValue":"5","DistanceKM":"0.0858826413670853","PostCode":"M1 5QA","Latitude":"53.472901","BusinessName":"Caffe Nero","Longitude":"-2.23997","RatingDate":"2011-01-18","AddressLine1":"","AddressLine2":"8A Oxford Road","AddressLine3":"Manchester"},{"id":"171089","RatingValue":"5","DistanceKM":"0.0858826413670853","PostCode":"M1 5QA","Latitude":"53.472901","BusinessName":"Greggs","Longitude":"-2.23997","RatingDate":"2011-01-18","AddressLine1":"","AddressLine2":"10 Oxford Road","AddressLine3":"Manchester"},{"id":"171185","RatingValue":"5","DistanceKM":"0.0858826413670853","PostCode":"M1 5QA","Latitude":"53.472901","BusinessName":"Holiday Inn Express","Longitude":"-2.23997","RatingDate":"2011-03-17","AddressLine1":"","AddressLine2":"2-4 Oxford Road","AddressLine3":"Manchester"},{"id":"171382","RatingValue":"1","DistanceKM":"0.0858826413670853","PostCode":"M1 5QA","Latitude":"53.472901","BusinessName":"Kukoos","Longitude":"-2.23997","RatingDate":"2013-11-18","AddressLine1":"","AddressLine2":"12a Oxford Road","AddressLine3":"Manchester"},{"id":"171404","RatingValue":"-1","DistanceKM":"0.0858826413670853","PostCode":"M1 5QA","Latitude":"53.472901","BusinessName":"Ladbrokes","Longitude":"-2.23997","RatingDate":"2010-11-09","AddressLine1":"","AddressLine2":"10B Oxford Road","AddressLine3":"Manchester"},{"id":"172281","RatingValue":"5","DistanceKM":"0.0858826413670853","PostCode":"M1 5QA","Latitude":"53.472901","BusinessName":"Subway","Longitude":"-2.23997","RatingDate":"2013-10-09","AddressLine1":"","AddressLine2":"12 Oxford Road","AddressLine3":"Manchester"},{"id":"171119","RatingValue":"5","DistanceKM":"0.100210503082758","PostCode":"M1 5GE","Latitude":"53.47208","BusinessName":"H & M Convenience Store","Longitude":"-2.241442","RatingDate":"2010-09-16","AddressLine1":"Student Village","AddressLine2":"Lower Chatham Street","AddressLine3":"Manchester"}] of type org.json.JSONArray cannot be converted to JSONObject
04-08 08:10:23.860    1656-1656/com.example.adam.jsonconnection D/AndroidRuntime﹕ Shutting down VM
04-08 08:10:23.860    1656-1656/com.example.adam.jsonconnection W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0xb2cbdb20)
04-08 08:10:23.860    1656-1656/com.example.adam.jsonconnection E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.example.adam.jsonconnection, PID: 1656

JSONParser Class

   package com.example.adam.jsonconnection;

import android.util.Log;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;


public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";


    // constructor
    public JSONParser() {
    }
    public JSONObject getJSONFromUrl(String url) {

        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            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();
        } 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;
    }
}

MainActivity Class

    package com.example.adam.jsonconnection;

import android.os.StrictMode;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;


public class MainActivity extends ActionBarActivity {



    //URL to get JSON Array
    private static String url = "";

    //JSON Node Names
    private static final String TAG_NEAREST = "nearest";
    private static final String TAG_BusinessName = "BusinessName";

    JSONArray nearest = null;



    @Override
    protected void onCreate(Bundle savedInstanceState) {

        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Creating new JSON Parser
        JSONParser jParser = new JSONParser();

        // Getting JSON from URL
        JSONObject json = jParser.getJSONFromUrl(url);
        try {
            // Getting JSON Array
            nearest = json.getJSONArray(TAG_NEAREST);
            JSONObject c = nearest.getJSONObject(0);

            // Storing  JSON item in a Variable
            String businessName = c.getString(TAG_BusinessName);


            //Importing TextView
            final TextView BusinessNameText = (TextView)findViewById(R.id.BusinessName);

            //Set JSON Data in TextView
            BusinessNameText.setText(businessName);

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


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}
2
  • 1
    As in log org.json.JSONArray cannot be converted to JSONObject Commented Apr 8, 2015 at 12:42
  • Is this ThreadPolicy thingy a way you can run server communication in UI thread? I would not recommend that. Have a look at loopj, it makes server communication way, way easier! Commented Apr 8, 2015 at 12:56

3 Answers 3

1

You have a JSONArray and you're attempting to create a JSONObject object with it.

Simple change your code to:

try {
    jObj = new JSONArray(json);
} catch (JSONException e) {
    Log.e("JSON Parser", "Error parsing data " + e.toString());
}

Or edit your response so that it is a json object.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for the help you have given me here, I now have another error, I have changed the code in the JSONParser class to what you said and the code in the main activity to nearest = json.getJSONArray(Integer.parseInt(TAG_NEAREST)); and the error below now shows..04-08 09:31:35.160 1631-1631/com.example.adam.jsonconnection E/Buffer Error﹕ Error converting result java.lang.NullPointerException: lock == null 04-08 09:31:35.160 1631-1631/com.example.adam.jsonconnection E/JSON Parser﹕ Error parsing data org.json.JSONException: End of input at character 0 of –
It seems like you're trying to parse the string TAG_NEAREST (which is simply "nearest")?
0

Your JSON is an Array from root, so you must change from:

JSONObject json = jParser.getJSONFromUrl(url);

to

JSONArray json = jParser.getJSONFromUrl(url);

and return a JSONArray from getJSONFromUrl

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

1 Comment

Thank you for the help you have given me here, I now have another error, I have changed the code in the JSONParser class to what you said and the code in the main activity to nearest = json.getJSONArray(Integer.parseInt(TAG_NEAREST)); and the error below now shows..04-08 09:31:35.160 1631-1631/com.example.adam.jsonconnection E/Buffer Error﹕ Error converting result java.lang.NullPointerException: lock == null 04-08 09:31:35.160 1631-1631/com.example.adam.jsonconnection E/JSON Parser﹕ Error parsing data org.json.JSONException: End of input at character 0 of
0

I suggest you to use:

jsonObject.optString("your_key");

instead of:

jsonObject.getString("your_key");

this will automatically handle possible "null" values

Comments

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.