我正在尝试解析JSON,但也允许用户输入部分JSON网址。因此,当网址“看起来”正确但没有任何结果时,会出现这种情况。这会导致NullPointerException。为了阻止我的代码崩溃,我必须抓住这个错误。我知道你不应该这样做,所以有人能告诉我一个更好的方法来解决这个问题吗?抱歉,因为我对Java / Android还不熟悉。
protected String doInBackground(String... params) {
ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
try {
String url_select = Final;
JSONObject json = jParser.makeHttpRequest(url_select,
"GET", param);
articles = json.getJSONObject("primaryTopic");
regadress = articles.getJSONObject("RegAddress");
try{
town = regadress.getString("PostTown");
}
catch (JSONException e2){
Log.e("JSONException", e2.toString());
town = regadress.getString("AddressLine2");
}
title = articles.getString("CompanyName");
description = articles.getString("CompanyStatus");
}
catch (java.lang.NullPointerException e) {
Log.e("NullPointerException", e.toString());
progressDialog.dismiss();
//showButtonDialog();
}
catch (IllegalStateException e3) {
Log.e("IllegalStateException", e3.toString());
e3.printStackTrace();
}
catch (JSONException e5) {
progressDialog.dismiss();
//showButtonDialog();
Log.e("JSONException", e5.toString());
e5.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String s) {
try {
String newTitle = Html.fromHtml(title).toString();
txtTitle.setText(newTitle);
String newDesc = Html.fromHtml(description).toString();
txtDesc.setText(newDesc);
String newTown = Html.fromHtml(town).toString();
txtTown.setText(newTown);
progressDialog.dismiss();
} catch (Exception e) {
Log.e("JSONException", "Error: " + e.toString());
}
}