What is The meaning of org.json.JSONException in A

2019-09-18 05:42发布

问题:

I am developing an Application of JSON object Which Returns data into ListView.

In That One Parameter Need to be passed which is Uid of User.

My Code for Async is:

class  AsyncCallWebServicereceiveHistory extends AsyncTask<String, String, String>
{
    ProgressDialog progressDialog;

    @Override
    protected void onPreExecute()
    {
        super.onPreExecute();
        progressDialog = new ProgressDialog(ReceiveHistory.this);
        progressDialog.setTitle("Loading");
        progressDialog.setMessage("Please wait");
        progressDialog.setCancelable(false);
        progressDialog.setIndeterminate(true);
        progressDialog.show();
    }

    @Override
    protected String doInBackground(String... aurl)
    {
        Log.v("receiveHistory","Do in BG-1");
        uid=global.get_user_id();
        try
        {
            HttpPost postMethod = new HttpPost("http://demo1.idevtechnolabs.com/RChatAPI/receive_history.php");

            List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
            postParameters.add(new BasicNameValuePair("uemail", uid));
            BufferedReader bufferedReader = null;

            HttpClient client = new DefaultHttpClient();
            HttpResponse response = null;

            response = client.execute(postMethod);
            final int statusCode = response.getStatusLine().getStatusCode();

            Log.v("Album ::","Response:::--->"+response.toString());
            Log.v("Album ::","Status Code:::--->"+statusCode);

            bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            StringBuffer stringBuffer = new StringBuffer("");
            String line = "";
            String LineSeparator = System.getProperty("line.separator");
            while ((line = bufferedReader.readLine()) != null)
            {
                stringBuffer.append(line + LineSeparator);
            }
            bufferedReader.close();

            //-------------CONVERT DATA TO JSON---------------------------------

            try
            {
                String myjsonstring = stringBuffer.toString();

                JSONArray jsonArray = new JSONArray(myjsonstring);

                JSONObject jsonObj = null;

                jsonObj = jsonArray.getJSONObject(0);
                code = jsonObj.getString("code");
                receiveMsgData.clear();

                Log.v("Home ::","Code:::--->"+code);

                code="0";
                if(code.equals("0"))
                {
                    for(int i=0; i<jsonArray.length();i++)
                    {

                            jsonObj = jsonArray.getJSONObject(i);
                            uname=jsonObj.getString("name");
                            uage = jsonObj.getString("age");
                            usex = jsonObj.getString("sex");
                            body = jsonObj.getString("country");
                            text= jsonObj.getString("text");

                            HashMap<String, String> tmp_album = new HashMap<String, String>();
                            tmp_album.put("receive_data", "Text");
                            Log.v("receive History","receive Data");
                            receiveMsgData.add(tmp_album);

                    }
                }
                catch (Exception e)
                {
                    Log.v("Home ::","Call JSON Exception in get Album in List--->"+e.toString());
                    e.printStackTrace();
                }
            }
            catch (Exception e)
            {
                Log.v("Exception: Get get Album in List","Name-"+e.toString());
                e.printStackTrace();
            }

            return code;
        }

        @Override
        protected void onPostExecute(String code)
        {
            if(code.equals("0"))
            {
                Receive_History_Custom_Adapter adapter = new Receive_History_Custom_Adapter(getApplicationContext(), receiveMsgData);
                lv.setAdapter(adapter);

            }
            else
            {
                Toast.makeText(getApplicationContext(), "Data not found", Toast.LENGTH_SHORT).show();
            }

            try
            {
                progressDialog.dismiss();
                progressDialog = null;
            }
            catch (Exception e)
            {
                // nothing
            }
        }
    }
}

And I got Following Exception:

Call JSON Exception in get Album in List--->org.json.JSONException: Value [] at 0 of type org.json.JSONArray cannot be converted to JSONObject

My Json Responce Is:

[
    {
        "code":"0", "user_id":"21", "msg_id":"115", "name":"Sagar", "age":"18", "sex":"Male", "country":
        " India", "text":"hi", "photo":"demo.idevtechnolabs.com", "cnt":"1"
    },
    {
        "code":"0", "user_id":"18", "msg_id":"114", "name":"Ramani", "age":"20", "sex":"Male", "country":
        "Pakistan", "text":"hi", "photo":"demo.idevtechnolabs.com", "cnt":"1"
    }
]

Can anyone tell me what is the cause of this and how can I solve this please.

Thanks in advance!

回答1:

I think you are trying to add every item from JSONArray to the list of messages if the code of this item equals to 0. If so, your code is wrong and it's easier to re-write it than just explain:

try {
    String myjsonstring = stringBuffer.toString();
    JSONArray jsonArray = new JSONArray(myjsonstring);
    receiveMsgData.clear();
    for (int i = 0; i < jsonArray.length(); i++) {
        if (jsonArray.getJSONObject(i).getInt("code") == 0) {
            JSONObject data = jsonArray.getJSONObject(i);
            HashMap<String, String> tmp_album = new HashMap<String, String>();
            tmp_album.put("name", data.getString("name"));
            tmp_album.put("age", data.getString("age"));
            tmp_album.put("sex", data.getString("sex"));
            tmp_album.put("country", data.getString("country"));
            tmp_album.put("text", data.getString("text"));
            receiveMsgData.add(tmp_album);
        }
    }

} catch (Exception e) {
    Log.v("Home ::", "Call JSON Exception in get Album in List--->" + e.toString());
    e.printStackTrace();
}

Here we are iterating over the JSONArray and check if code is equal to 0. If it's equal, we put the necessary fields to the temporary HashMap and then append it to the messages list.