在使用JSON数据时,如何防止我的应用程序意外崩溃,“关闭”,而代之以处理
技术问答
231 人阅读
|
0 人回复
|
2023-09-12
|
在我的应用程序中,我有一个食物活动,用户通过用户输入的名称输入食物。MYSQL数据库要求食物。如果输入的食物不存在,数据库返回的字符串应为null。, ?7 s6 Q- j% ^: b0 o6 V' v" D
目前,当这种情况发生时,会出现异常,因为不可能null值解析为JSON数组。我的问题是:有没有办法防止我的应用程序被迫关闭?我能处理异常并显示吐司,告诉用户我没有找到要求的食物吗?. h/ r# z- A4 H. m( W( q0 F# x
我想防止应用程序崩溃,正常失败。, A, a3 J% f' e
请帮我。
2 Y5 z: u9 g0 P' ?* D2 T3 O我已经在我的应用程序中显示了相关代码。
5 x2 l* |9 Y. r# sprivate class LoadData extends AsyncTask { private JSONArray jArray;private String result = null;private InputStream is = null;private String entered_food_name=choice.getText().toString().trim();protected void onPreExecute() {}@Overrideprotected String doInBackground(Void... params) { try ArrayList nameValuePairs = new ArrayList(); 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 stringBufferedReader 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;}@Overrideprotected 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()); } }} # u5 R/ n% ~( t0 g5 P9 s% P4 M
解决方案: |
|
|
|
|
|