6

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();
        }
    }
}
user1742757
  • 61
  • 1
  • 3

2 Answers2

5

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.

Jade Byfield
  • 4,668
  • 5
  • 30
  • 41
1

onPostExecute() can never execute before doInBackground() finishes.

You must Know that only doInBackground() gets executed in Async Thread/Task whatever you call. and onPostExecute() will get executed in main UI thread itself.

Show how Have you called this task in the code .

And main thing you must check on is you must not use any of the data that is fetched from AsyncTask in the Main UIThread unless you are sure that Asynctask is finished.

Since there is a chance of it executing Before theAsyncTask finishes and Definitely you will get NULLException in that scenario.

Zombie
  • 1,965
  • 2
  • 20
  • 34