How do I prevent my app from crashing unexpectedly, “force close”, when using JSON data, and handle the exception instead?

谁说胖子不能爱 提交于 2019-12-11 06:58:18

问题


In my application, I have a food activity in which the user enters his/her food, and the app requests the food, by the name entered by the user, from a MYSQL database. In the case that the entered food not exist, the string returned by the database should be null.

Currently, when this happens, an exception to occurs since the null value cannot be parsed to a JSON array. My question is: "Is there a way to prevent my app from force closing? Can I handle the exception and display a toast notifying the user that the requested food was not found?" I would like to prevent the app from crashing, and, rather, fail gracefully.

Please help me.

I've shown the relevant code in my application..

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()); 
        }   
    }
}

回答1:


This will fix your code:

jArray = (result == null) ? new JSONArray() : new JSONArray(result);

Now that you have an empty JSONArray, you will be able to test for null JSONObjects later in your program. Many of the JSON methods return a JSONObject if one is found, of null if none exists.

You might also want to initialize your JSONObject with the no-argument JSON constructor, rather than simply setting it to null. It will avoid problems when passing it to other JSON methods (such as using it in a constructor to a JSONArray():

JSONObject json_data = new JSONObject();

Finally, if you're still getting JSONExceptions, it's because you're not actually passing a valid JSON string to the constructor. You can print out the value of result to the log:

Log.d("JSON Data", result);

You may see some SQL error text or if you retrieve from a web server, then an HTTP error code (404 is common if you don't have your url correct).

If your result does look like JSON, then you can verify whether it's actually valid JSON or not using the JSONLint validator. It will help you catch any errors you may have, especially if you're formatting the JSON yourself.




回答2:


Are you looking to capture the Exception and log it (remotely) to aid in crash reporting and debugging? I've used this package to remotely capture Exceptions and it works pretty good:

http://code.google.com/p/android-remote-stacktrace/



来源:https://stackoverflow.com/questions/10587599/how-do-i-prevent-my-app-from-crashing-unexpectedly-force-close-when-using-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!