我使用 AsyncTask 从网络获取 JSON,并在方法 doInBackground() 中解析 JSON。我在 onPreExecute() 中启动 ProgressDialog,并在 onPostExecute() 中关闭它。问题是我的对话框永远不会被关闭,然后我收到等待/强制关闭问题或模拟器只是卡住。我尝试从本地文件解析 JSON,它成功了。我在 doInBackground() 中的第二个 log.d() 从未被打印,只打印第一个。
我的 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;
关于java - 使用 AsyncTask 获取 JSON 时,ProgressDialog 永远不会被关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4648937/