【问题标题】:ProgressDialog is never dismissed when fetching JSON with AsyncTask使用 AsyncTask 获取 JSON 时,ProgressDialog 永远不会被关闭
【发布时间】:2011-01-10 16:24:00
【问题描述】:

我使用 AsyncTask 从 Web 获取 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;
    }

我在哪里做错了?

【问题讨论】:

    标签: java android json android-asynctask


    【解决方案1】:

    看起来您正试图将响应的内容读入缓冲区,然后使用它来创建返回数据的String 表示。错误在于您创建和使用缓冲区的方式。

    但是,既然您只需要一个String,这样做不是更容易吗:

    String jsontext = EntityUtils.toString(response.getEntity());
    

    你还需要

    import org.apache.http.util.EntityUtils;
    

    【讨论】:

    • Tnx,我把整个事情复杂化了。
    【解决方案2】:

    很明显,这条线陷入了无限循环:

    while (data.read(buffer) != -1);
    

    【讨论】:

      猜你喜欢
      • 2011-05-28
      • 2016-07-20
      • 1970-01-01
      • 2015-05-12
      • 2013-11-07
      • 1970-01-01
      • 2013-09-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多