2

JSON data:

{
"data": [
 {
   "id": 5,
   "name": "Deal One"
 },
 {
   "id": 6,
   "name": "Deal Two"
 },
 {
   "id": 7,
   "name": "Deal Three"
 }
]
}

onPostExecute, where JSONArray is being cast.

    @Override
    protected void onPostExecute(String result) {

        //this method will be running on UI thread
        ArrayList<String> dataList = new ArrayList<String>();
        pdLoading.dismiss();


        if(result.equals("no rows")) {

            // Do some action if no data from database

        }else{

            try {

                JSONArray jArray = new JSONArray(result);

                // Extract data from json and store into ArrayList
                for (int i = 0; i < jArray.length(); i++) {
                    JSONObject json_data = jArray.getJSONObject(i);
                    dataList.add(json_data.getString("name"));
                }

                strArrData = dataList.toArray(new String[dataList.size()]);

            } catch (JSONException e) {
                // You to understand what actually error is and handle it appropriately
                Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_LONG).show();
                Toast.makeText(MainActivity.this, result.toString(), Toast.LENGTH_LONG).show();
            }

        }

    }

What's the big idea behind all of this? Doing an autocomplete gig following this tutorial. I noticed their JSON looks very different from mine.

How can I fix the JSONArray error?

EDIT2

STACKTRACE: (edit 3: the error below happens when I follow everyone else's code)

01-19 14:41:15.442 6513-6513/gsi.xform W/System.err: org.json.JSONException: Value Connection of type java.lang.String cannot be converted to JSONObject
01-19 14:41:15.448 6513-6513/gsi.xform W/System.err:     at org.json.JSON.typeMismatch(JSON.java:111)
01-19 14:41:15.448 6513-6513/gsi.xform W/System.err:     at org.json.JSONObject.<init>(JSONObject.java:160)
01-19 14:41:15.448 6513-6513/gsi.xform W/System.err:     at org.json.JSONObject.<init>(JSONObject.java:173)
01-19 14:41:15.448 6513-6513/gsi.xform W/System.err:     at gsi.xform.MainActivity$AsyncFetch.onPostExecute(MainActivity.java:385)
01-19 14:41:15.448 6513-6513/gsi.xform W/System.err:     at gsi.xform.MainActivity$AsyncFetch.onPostExecute(MainActivity.java:288)
01-19 14:41:15.448 6513-6513/gsi.xform W/System.err:     at android.os.AsyncTask.finish(AsyncTask.java:651)
01-19 14:41:15.448 6513-6513/gsi.xform W/System.err:     at android.os.AsyncTask.-wrap1(AsyncTask.java)
01-19 14:41:15.448 6513-6513/gsi.xform W/System.err:     at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:668)
01-19 14:41:15.448 6513-6513/gsi.xform W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:102)
01-19 14:41:15.448 6513-6513/gsi.xform W/System.err:     at android.os.Looper.loop(Looper.java:148)
01-19 14:41:15.448 6513-6513/gsi.xform W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:5417)
01-19 14:41:15.448 6513-6513/gsi.xform W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
01-19 14:41:15.448 6513-6513/gsi.xform W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
01-19 14:41:15.448 6513-6513/gsi.xform W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

EDIT4:

Here is the doInBackground code:

    @Override
    protected String doInBackground(String... params) {
        try {

            // Enter URL address where your php file resides or your JSON file address
            url = new URL("http://myprivate.url?X-Authorization=token");

        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return e.toString();
        }
        try {

            // Setup HttpURLConnection class to send and receive data from php and mysql
            conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(READ_TIMEOUT);
            conn.setConnectTimeout(CONNECTION_TIMEOUT);
            conn.setRequestMethod("GET");

            // setDoOutput to true as we receive data
            conn.setDoOutput(true);
            conn.connect();

        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
            return e1.toString();
        }

        try {

            int response_code = conn.getResponseCode();

            // Check if successful connection made
            if (response_code == HttpURLConnection.HTTP_OK) {

                // Read data sent from server
                InputStream input = conn.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(input));
                StringBuilder result = new StringBuilder();
                String line;

                while ((line = reader.readLine()) != null) {
                    result.append(line);
                }

                // Pass data to onPostExecute method
                return (result.toString());

            } else {
                return("Connection error");
            }

        } catch (IOException e) {
            e.printStackTrace();
            return e.toString();
        } finally {
            conn.disconnect();
        }


    }
1
  • 1
    please include the stacktrace Commented Jan 19, 2017 at 16:25

3 Answers 3

3

result is a JSONObject not a JSONArray

   // fetch the object      
    JSONObject obj = new JSONObject(result);

   // fetch the data array
    JSONArray jArray = obj.getJSONArray("data");

    // Extract data from json and store into ArrayList
    for (int i = 0; i < jArray.length(); i++) {
        JSONObject json_data = jArray.getJSONObject(i);
        dataList.add(json_data.getString("name"));
    }

{                     // beginning of JSONObject
"data": [             // nested JSONArray
 {                    // nested JSONObject inside JSONArray
   "id": 5,  
   "name": "Deal One"
 },
 {
   "id": 6,
   "name": "Deal Two"
 },
 {
   "id": 7,
   "name": "Deal Three"
 }
]
}  // ending of JSONObject

Info : The other issue was due to Runtime-Permission implementation with flow of execution mean permission was not given at the time of establishing the internet connection.

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

9 Comments

I thought this was it, but the same error happens with your modification.
@Rosenberg add the complete current stack trance and try clean and build if you are using instant run
I just added the logcat
@Rosenberg add this e.printStackTrace() in catch block to see the complete exception , this is all unwanted info
@Rosenberg i have tested your json result against my code and it's working without any issue and try to see what is at line 385 in your MainActivity
|
0

just a little mistake in your JSON there is On Object , has an array called "data"

  JSONObject obje = new JSONObject(results);
  JSONArray jArray = obje.getJSONArray("data");

then it's the same like you. just remember that {} for objects , and [] for arrays in JSON

Comments

0

You are converting your string to jsonArray where your response is a jsonObject:

Do this:

JSONObject jsnobject = new JSONObject(result);

JSONArray jsonArray = jsnobject.getJSONArray("data");


    for (int i = 0; i < jsonArray.length(); i++)
    {
        JSONObject data= jsonArray.getJSONObject(i);
        dataList.add(data.getString("name"));
    }

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.