使用“ AsyncTask”并从请求中获取数据。但是有时响应为空或为null,这就是我的应用程序崩溃的原因。
如果这样的反应,请看图片
我尝试将响应存储在字符串中,然后检查是否不为null,然后继续进行操作。但是string为null并继续进行操作。
此代码用于检查jsonstr是否不为null,然后再输入是否其他明智的吐司消息显示某些错误,但jsonstr为null且应用程序已崩溃如何处理,请提供解决方案,我是初学者在stackover流中。
private class GetProfileDetails extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... strings) {
String getprofileUrl =
"http://api.digitalegram.com/UserProfile.aspx?uid=" + id + "";
HttpHandler sh = new HttpHandler();
String jsonStr = sh.makeServiceCall(getprofileUrl);
if (jsonStr != null) {
try {
JSONObject jsobobj = new JSONObject(jsonStr);
statusprofile = jsobobj.getString("status")
if (Integer.parseInt(statusprofile) == 0) {
JSONArray jsonArray = jsobobj.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject response = jsonArray.getJSONObject(i);
oname = response.getString("OwnerName");
mobole = response.getString("MobileNo1");
EmailId = response.getString("EmailId");
}
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(),"Json parsing error: " + e.getMessage(),Toast.LENGTH_LONG).show();
}
});
}
} else
{
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(),"Couldn't get json from server. Check LogCat for possible errors!",Toast.LENGTH_LONG).show();
}
});
}
return result;
}
答案 0 :(得分:-1)
删除Toast消息并进行检查。
HttpHandler sh = new HttpHandler();
String jsonStr = sh.makeServiceCall(getprofileUrl);
if (jsonStr != null) {
try {
JSONObject jsobobj = new JSONObject(jsonStr);
statusprofile = jsobobj.getString("status")
if (Integer.parseInt(statusprofile) == 0) {
JSONArray jsonArray = jsobobj.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject response = jsonArray.getJSONObject(i);
oname = response.getString("OwnerName");
mobole = response.getString("MobileNo1");
EmailId = response.getString("EmailId");
}
}
return jsonStr;
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
}
}else
{
Log.e(TAG, "Couldn't get json from server.");
}
return "";
}