在我的应用程序中,我有一个食物 Activity ,用户在其中输入他/她的食物,应用程序根据用户输入的名称从 MYSQL 数据库中请求食物。如果输入的食物不存在,数据库返回的字符串应该为空。
目前,当出现这种情况时,由于无法将 null 值解析为 JSON 数组,因此会出现异常。我的问题是:“有没有办法防止我的应用程序强制关闭?我可以处理异常并显示提示通知用户找不到请求的食物吗?”我想防止应用程序崩溃,而是优雅地失败。
请帮帮我。
我已经在我的应用程序中显示了相关代码..
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());
}
}
}
最佳答案
这将修复您的代码:
jArray = (result == null) ? new JSONArray() : new JSONArray(result);
现在您有了一个空的 JSONArray,稍后您将能够在您的程序中测试空 JSONObject。许多 JSON 方法在找到时返回一个 JSONObject,如果不存在则返回 null。
您可能还想使用无参数 JSON 构造函数初始化您的 JSONObject,而不是简单地将其设置为 null。将它传递给其他 JSON 方法时会避免出现问题(例如在构造函数中将其用于 JSONArray():
JSONObject json_data = new JSONObject();
最后,如果您仍然收到 JSONException
,那是因为您实际上没有将有效的 JSON 字符串传递给构造函数。您可以将 result
的值打印到日志中:
Log.d("JSON Data", result);
您可能会看到一些 SQL 错误文本,或者如果您从 Web 服务器检索,则会看到 HTTP 错误代码(如果您的 URL 不正确,则常见 404)。
如果您的结果看起来 像 JSON,那么您可以使用 JSONLint validator 验证它是否实际上是有效的 JSON .它将帮助您捕获可能遇到的任何错误,尤其是当您自己格式化 JSON 时。
关于android - 如何防止我的应用程序在使用 JSON 数据时意外崩溃 "force close"并改为处理异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10587599/