[英]ProgressDialog is never dismissed when fetching JSON with AsyncTask
我使用AsyncTask从网络上获取JSON,并且还在方法doInBackground()中解析JSON。 我在onPreExecute()中启动我的progressDialog,然后在onPostExecute()中将其关闭。 问题是我的对话框永远不会消失,然后我收到等待/强制关闭问题,或者模拟器只是冻结。 我尝试从本地文件中解析JSON,并且可以正常工作。 我的第二个log.d()在doInBackground()中从未打印,只有第一个。
我的doInBackground()看起来像这样:
private class DownloadFilesTask extends AsyncTask<String, Void, String> {
protected String doInBackground(String... url) {
DefaultHttpClient httpClient = new DefaultHttpClient();
URI uri;
InputStream data=null;
String x="";
try {
uri = new URI(url[0]); //url of my JSON file
HttpGet method = new HttpGet(uri);
HttpResponse response = httpClient.execute(method);
data = response.getEntity().getContent();
byte [] buffer = new byte[data.available()];
Log.d("First: ","ziv");
while (data.read(buffer) != -1);
Log.d("Second: ",Integer.toString(buffer.length));
String jsontext = new String(buffer);
JSONArray entries = new JSONArray(jsontext);
x = "JSON parsed.\nThere are [" + entries.length() + "]\n\n";
int i;
for (i=0;i<entries.length();i++)
{
JSONObject post = entries.getJSONObject(i);
x += "------------\n";
x += "Date:" + post.getString("created_at") + "\n";
x += "Post:" + post.getString("text") + "\n\n";
}
}
catch (IOException je)
{
je.printStackTrace();
}
catch (URISyntaxException ur) {
ur.printStackTrace();
}
catch (JSONException je) {
tvData.setText("Error w/file: " + je.getMessage());
}
return x;
}
我在哪里做错了?
看起来您正在尝试将响应的内容读取到缓冲区中,然后使用该缓冲区创建返回数据的String
表示形式。 错误在于您创建和使用缓冲区的方式。
但是,由于只需要一个String
,这样做会不会更容易:
String jsontext = EntityUtils.toString(response.getEntity());
您还需要
import org.apache.http.util.EntityUtils;
显然,这条线陷入了无限循环:
while (data.read(buffer) != -1);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.