我正在使用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數組。沒有檢查也沒有工作。 –