2

In some of my applications that talk to a server and get a response using http I use json to format the data server side and when it gets to the device I use something similar to this code which I found on stackoverflow:

private class LoadData extends AsyncTask<Void, Void, String> 
{ 
private  JSONArray jArray;
private  String result = null;
private  InputStream is = null;
private String entered_food_name=choice.getText().toString().trim();
protected void onPreExecute() 
{
}

@Override
protected String doInBackground(Void... params) 
{
try {
ArrayList<NameValuePair> nameValuePairs = new            ArrayList<NameValuePair>();
HttpClient httpclient = new DefaultHttpClient(); 
HttpPost httppost = new HttpPost("http://10.0.2.2/food.php");
nameValuePairs.add(new BasicNameValuePair("Name",entered_food_name));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,"UTF-8"));
HttpResponse response = httpclient.execute(httppost);

HttpEntity entity = response.getEntity();
 is = entity.getContent();

    //convert response to string

BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"),8);
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
        sb.append(line);
    }

    is.close();


    result =sb.toString();
    result = result.replace('\"', '\'').trim();

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


return result;  

}

@Override
protected void onPostExecute(String result) 
{  
try{

    String foodName="";
    int Description=0;

    jArray = new JSONArray(result); // here if the result is null an exeption will occur
    JSONObject json_data = null;

    for (int i = 0; i < jArray.length(); i++) {
        json_data = jArray.getJSONObject(i);
        foodName=json_data.getString("Name");
        .
        .
        .
        .
        .
    } 
    catch(JSONException e){ 
        **// what i can do here to prevent my app from crash and 
        //  make toast " the entered food isnot available " ????**
        Log.e("log_tag", "parssing  error " + e.toString()); 
    }   
}
}

I tried to use the solution on the page where I found this code. heres the link by the way How do I prevent my app from crashing unexpectedly, "force close", when using JSON data, and handle the exception instead?

I tried checking my json response with online validators and the json returned is valid. Im thinking that when users are in a poor coverage area the connection momentarily breaks or something causes the json to be broken which causes a json exception even though I have tried the method suggested in the thread I posted in that link. So I would like to be able to validate the JSON when it gets to the phone so if its valid I can proceed and if not than I would like to try and fix it or at least not try to pass a broken and not properly formatted json array into one of the methods that causes the JSONException.

Any tips on validating the string I get in the response to make sure its valid JSON would be awesome.

Edit: added stack dump related to problem

org.json.JSONException: Value null at results of type org.json.JSONObject$1 cannot be     converted to JSONArray
at org.json.JSON.typeMismatch(JSON.java:96)
at org.json.JSONObject.getJSONArray(JSONObject.java:548)
at it.cores.Activity$GetM.doInBackground(Activity.java:1159)
at it.cores.Activity$GetM.doInBackground(Activity.java:1)
at android.os.AsyncTask$2.call(AsyncTask.java:185)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
at java.util.concurrent.FutureTask.run(FutureTask.java:138)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
at java.lang.Thread.run(Thread.java:1019)
Community
  • 1
  • 1
James andresakis
  • 5,335
  • 9
  • 53
  • 88
  • Assuming you're wrapping the JSONArray instantiation inside a try catch block, then aren't you protecting your app from force closing? All you need to do is check that `jArray` isn't null before using it. By instantiating `JSONArray` with the JSON data contained in the string, will be a form of validation, as it won't be able to instantiate otherwise. – BDFun Jun 10 '12 at 00:48
  • The response string coming back is never null. What is happening is that the JSON is sometimes broken somehow. I cant reproduce the errors i see in my crash repo but from the stack dumps I can see that its caused by org.json.JSONException: Value null at results of type org.json.JSONObject$1 cannot be converted to JSONArray and thats inside a try catch. – James andresakis Jun 10 '12 at 00:55
  • From everything Ive read you will get that exception when trying to parse broken or improperly formatted json – James andresakis Jun 10 '12 at 01:07
  • I've written an app that processes JSON data from a web service, and I've never seen a `JSONException` escape the catch clause. Are you sure you're interpreting the stack dumps correctly? The previous comment sounds like you're reading the output of the log method call in the catch clause. Can you post up the relevant part of the stack trace? – BDFun Jun 10 '12 at 01:14
  • Sure but Im using ACRA to catch the stack dump when ever my apps crash. I added the dump to my question. – James andresakis Jun 10 '12 at 01:25
  • I've never used ACRA, but you're positive that the stack trace you've added is what is causing it to crash, and not just an innocuous log entry? Have you tried hard coding the `result` string in `onPostExecute` to a string that you know is invalid, to force a JSONException? That way you can see if it really is escaping the catch clause, or if it is something else. – BDFun Jun 10 '12 at 01:52
  • If I dump my result string into the logcat it comes out just fine from the server. The doesnt show up all the time in my repository. It shows up randomly every once in a while. I cant reproduce it unless I set up a separate script that deliberately sends invalid JSON. When I deliberately send invalid json bingo exception thrown. From the developers docs it says that this kind of exception is almost always unrecoverable and that users should just throw a new exception which Ive tried but I get the same error twice at that point lol. What Id really like to do is validate before parsing. – James andresakis Jun 10 '12 at 02:06
  • @Jamesandresakis I have a similar problem, may be you can help me. Please try to see my post: http://stackoverflow.com/questions/38030215/android-explote-trying-to-handle-receiving-null-json-data-from-my-host – Faustino Gagneten Jun 28 '16 at 14:48

1 Answers1

2

You have to make sure you do the parsing after doing a null check/or any other validation like checking if it contains the response code before doing any operation on the String result.

protected void onPostExecute(String result) 
{  
try{

    String foodName="";
    int Description=0;

if(result!=null)//Do your validation for result

{
    jArray = new JSONArray(result); // here if the result is null an exeption will occur
    JSONObject json_data = null;

    for (int i = 0; i < jArray.length(); i++) {
        json_data = jArray.getJSONObject(i);
        foodName=json_data.getString("Name");
        .
        .
        .
        .
        .
    } 
 }
   catch(JSONException e){ 
        **// what i can do here to prevent my app from crash and 
        //  make toast " the entered food isnot available " ????**
        Log.e("log_tag", "parssing  error " + e.toString()); 
    }   
}
donfuxx
  • 11,277
  • 6
  • 44
  • 76
O__O
  • 950
  • 1
  • 9
  • 17
  • Yeah for the time being thats what Ive done but I wanted to be positive that I can handle cases when the json makes it to the device and its not formatted properly. I cant reproduce the error that some people seem to get "out in the wild". Do you know of anyway I could possibly validate my JSON after its come to the device and the result string is not null. – James andresakis Jun 10 '12 at 01:50
  • 1
    It would be good if you can check the response code you get from the server(like some 200 for success) also along with the null check – O__O Jun 10 '12 at 01:58
  • The problem isnt the response from the server which for me comes back just as expected. The problem seems to be in the case of poor network conditions the json becomes broken some how and since its no longer formatted properly I get JSONException. – James andresakis Jun 10 '12 at 02:22
  • @donfuxx please I have a similar problem, may be you can help me, see my post at: http://stackoverflow.com/questions/38030215/android-explote-trying-to-handle-receiving-null-json-data-from-my-host – Faustino Gagneten Jun 28 '16 at 14:50