Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why onPostExecute execute before doInBackground finish in AsyncTask

I was trying to create a AsyncTask to get some data from server side. But it reports a Null pointer exception in onPostExecute() in line "IOUtils.copy((response_.getEntity().getContent()), writer);" I use some logs to see what happens and found log 1 and 3 were printed but log 2 was not. Why onPostExecute was executed before client.executed() finish? Anyone can give some suggestions?

private class GetForm extends AsyncTask<String, Integer, Object> {
    private HttpResponse response_;
    private Exception exception_;
    private String url_;

    public GetForm(String url) {
        super();
        url_ = url;
    }
    protected Object doInBackground(String... params) {
        try {
            Log.i("mylog","inside doInbackground 1.");
            HttpClient client = new DefaultHttpClient();
            HttpGet request = new HttpGet(url_);
            response_ = client.execute(request);
                            Log.i("mylog","inside doInbackground 2.");

        } catch (Exception e) {
            exception_ = e;
        }
        return response_;
    }
    @Override
    protected void onPostExecute(Object o) {
        // Your current UI stuff here.
        Log.i("mylog","inside onPostExecute 3.");
        StringWriter writer = new StringWriter();
        try{
            IOUtils.copy((response_.getEntity().getContent()), writer);
        ......

        }catch(IOException e) {
            e.printStackTrace();
        }
    }
}
like image 364
user1742757 Avatar asked Oct 13 '12 03:10

user1742757


1 Answers

It's unlikely that onPostExecute() was called first, and more likely that an exception was thrown in your doInBackground()..and also why Log 2 wasn't printed. Check the Warning or Debug pages in your LogCat. Also, you should print both exceptions separately.

like image 103
Jade Byfield Avatar answered Oct 15 '22 18:10

Jade Byfield