开发者

ProgressDialog is never dismissed when fetching JSON with AsyncTask

I fetch JSON from the web with AsyncTask and also parse JSON in method doInBackground(). I start my progressDialog in onPreExecute() and dismiss it in onPostExecute(). The problem is that my dialog is never dismissed and then i receive wait/force close question or the emulator just freezes. I tried parsing JSON from local file and it worked. My second log.d() in doInBackground() is never printed, only the first one.

My doInBackground() looks like this:

private class DownloadFilesTask extend开发者_如何学Gos 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;
    }

Where am i doing mistekes?


It looks like you are trying to read the content of the response into a buffer, then using that to create a String representation of the returned data. The mistake is in the way you are creating and using the buffer.

However, since you just need a String, wouldn't it be easier to do this:

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

You will also need

import org.apache.http.util.EntityUtils;


Rather obviously, this line is stuck in an infinite loop:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜