我如何prevent我的应用程序意外崩溃,"强制关闭&QUOT ;,使用JSON数据时,并处理异常呢? [英] How do I prevent my app from crashing unexpectedly, "force close", when using JSON data, and handle the exception instead?

查看:129
本文介绍了我如何prevent我的应用程序意外崩溃,"强制关闭&QUOT ;,使用JSON数据时,并处理异常呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序,我在其中用户输入他/她的食物食物的活动,以及应用程序要求的食品,由用户输入,从一个MySQL数据库的名称。在所输入的食品不存在的情况下,由数据库返回的字符串应该为null。

目前,发生这种情况时,发生异常以来空值不能被解析到一个JSON数组。我的问题是:有没有办法为prevent我的应用程序从强制关闭我能处理异常,并显示敬酒通知要求的食品没有找到用户?我想prevent崩溃的应用程序,并且,相反,失败的优雅。

请帮助我。

我已经展示了相关的code在我的应用程序。

 私有类LoadData扩展的AsyncTask<太虚,太虚,字符串>
    {
私人JSONArray jArray;
私人字符串结果= NULL;
私人InputStream为= NULL;
。私有String entered_food_name = choice.getText()的toString()修剪();
在preExecute保护无效()
{
}@覆盖
保护字符串doInBackground(无效... PARAMS)
{
   尝试{
    ArrayList的<&的NameValuePair GT; namevaluepairs中=新的ArrayList<&的NameValuePair GT;();
    HttpClient的HttpClient的=新DefaultHttpClient();
    HttpPost httppost =新HttpPost(http://10.0.2.2/food.php);
    nameValuePairs.add(新BasicNameValuePair(名,entered_food_name));
    httppost.setEntity(新UrlEn codedFormEntity(namevaluepairs中,UTF-8));
    HTT presponse响应= httpclient.execute(httppost);    HttpEntity实体= response.getEntity();
     是= entity.getContent();        //响应转换为字符串读者的BufferedReader =新的BufferedReader(新的InputStreamReader(是,UTF-8),8);
        StringBuilder的SB =新的StringBuilder();
        串线= NULL;
        而((行= reader.readLine())!= NULL){
            sb.append(线);
        }        is.close();
        结果= sb.toString();
        。结果= result.replace('\\','\\'')修剪();    }
    赶上(例外五){
        Log.e(log_tag,连接+ e.toString());
    }
    返回结果;}@覆盖
保护无效onPostExecute(字符串结果)
{
    尝试{        串foodName =;
        int描述= 0;        jArray =新JSONArray(结果); //此处若结果为空将发生exeption
        JSONObject的json_data = NULL;        的for(int i = 0; I< jArray.length();我++){
            json_data = jArray.getJSONObject(ⅰ);
            foodName = json_data.getString(名称);
            。
            。
            。
            。
            。
        }
        赶上(JSONException E){
            ** //我可以做什么这里$ P $坠机pvent我的应用程序和
            //使土司输入食品可用状态并没有???? **
            Log.e(log_tag,parssing错误+ e.toString());
        }
    }
}


解决方案

这将解决您的code:

  jArray =(结果== NULL)?新JSONArray():新的JSONArray(结果);

现在你有一个空的JSONArray,你将可以在你的程序之后测试空一个JSONObjects。许多JSON方法返回一个JSONObject如果找到,返回null;如果不存在。

您可能也想用的无参数的JSON构造函数初始化你的JSONObject,而不是简单地将其设置为null。

的:它传递给其他的JSON方法(如在一个构造用它来一个JSONArray()时,它会​​避免出现问题

 的JSONObject json_data =新的JSONObject();


最后,如果你仍然得到 JSONException S,那是因为你没有真正传递一个有效的JSON字符串的构造。您可以打印出结果的值到日志:

  Log.d(JSON数据,结果);

您可能会看到一些SQL错误的文字,或者如果您从Web服务器中检索,然后HTTP错误code(404是常见的,如果你没有你的网址是正确的)。

如果您的结果并的的像JSON,那么你可以验证它是否是真正有效的JSON或不使用的 JSONLint验证。这将帮助您捕捉你可能有任何错误,特别是如果你自己格式化JSON。

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

解决方案

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.

这篇关于我如何prevent我的应用程序意外崩溃,&QUOT;强制关闭&QUOT ;,使用JSON数据时,并处理异常呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆