我正在使用Async任务类来解析'doInBackground'中的JSON文件,并将结果添加到'onPostExecute'中的列表视图中,但我使用的进度对话框永远不会停止,结果永远不会结束出版。我使用此代码:Android AsyncTask永远不会完成
public class JSONTask extends AsyncTask<String,String,JSONObject>
{
private ProgressDialog pDialog;
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AnswerActivity.this);
pDialog.setMessage("Getting Answers ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
@Override
protected JSONObject doInBackground(String... params) {
try {
answersJson = makeRequest(requestUrl);
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return answersJson;
}
@Override
protected void onPostExecute(JSONObject jsonObject) {
try {
if(mJSONArr!=null){
mJSONArr = jsonObject.getJSONArray("items");
for(int i=0;i<mJSONArr.length();i++)
{
String val = null;
ob2 = mJSONArr.getJSONObject(i);
if(ob3!=null){ob3 = ob2.getJSONObject("owner");}
answers[i] = new Answer(ob2.getString("body"),ob3.getString("display_name"),ob2.getString("score"));
}
adapter = new AnswersAdapter(AnswerActivity.this,
R.layout.answer_list_item, answers);
answerList.setAdapter(adapter);
pDialog.dismiss();}
//url = "https://api.stackexchange.com/2.2/search?order=desc&sort=activity&";
} catch (JSONException e) {
e.printStackTrace();
}
}
}
这是makeRequest的功能:
private JSONObject makeRequest(String url) throws IOException, JSONException {
JSONObject response;
String jsonString;
HttpClient httpclient = new DefaultHttpClient();
// create the request
HttpUriRequest request = new HttpGet(url);
request.addHeader("Accept-Encoding", "gzip");
// execute the request
HttpResponse resp = httpclient.execute(request);
StatusLine statusLine = resp.getStatusLine();
// check the request response status. Should be 200 OK
if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
Header contentEncoding = resp.getFirstHeader("Content-Encoding");
InputStream instream = resp.getEntity().getContent();
// was the returned response gzip'ed?
if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
instream = new GZIPInputStream(instream);
}
BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
StringBuilder responseString = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
responseString.append(line);
}
jsonString = responseString.toString();
response = new JSONObject(jsonString);
} else {
resp.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
return response;
}
我该如何解决这个问题,并在列表中看到的结果看?
谢谢!
您在mJSONArr那里进行此项检查。它可能是空的。这就是为什么没有任何工作。我不确定你需要mJSONArr在那里。 – ElDuderino
我的确需要这个数组,因为响应给了我一个带有json对象的JSON数组。没有检查也没有工作。 –