Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onPostExecute does not get called

I have an Activity (RecipiesActivity) that is opened by clicking on the "Next" button of the Main Activitiy of my application.

In the RecipiesActivity onCreate, I want to call a webservice in an AsyncTask. For now, since I have not implemented the webservice yet, I am just calling a webservice provided by bitly (but this is irrelevant to my problem).

The problem is that although the webservice gets called and no exception is thrown, a result is return from the doInBackground, but my onPostExecute is not called. I have done some research and I have found the possible reasons as listed below - but none seem to be my case:

  • onPostExecute parameters do not match the AsyncTask parameters - in my case they match
  • A bug in android that does not allow the AsyncTask to be executed in the UI thread. It is supposadely overcomes by using Class.forName("android.os.AsyncTask") - I tried this and did not make any difference
  • AsyncTask is not started from the UI thread - in my case I believe it is
  • doInBackground does not return - in my case it does, I have stepped through it with the debugger
  • @Override is not used before onPostExecute - in my case I am using @Override

The code is below:

public class RecipiesActivity extends Activity {

    private TextView tv;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_recipies); 
        tv = (TextView) findViewById(R.id.Response);

        //Start the WS call in an AsyncTask 
        new CallWS().doInBackground("https://api-ssl.bitly.com/v3/shorten?login=maskedLogin&apiKey=maskedKey&longUrl=http%3A%2F%2Fgoogle.com%2F");          
    }

    private class CallWS extends AsyncTask<String, Integer, String>
    {
        @Override
        protected String doInBackground(String... params) {

            String result = null;
            HttpClient httpClient = new DefaultHttpClient(); 
            HttpContext localContext = new BasicHttpContext(); 
            HttpGet get_request = new HttpGet(params[0]); 
            try
            {
                HttpResponse httpResponse = httpClient.execute(get_request, localContext);
                //int responseCode = httpResponse.getStatusLine().getStatusCode();
                HttpEntity entity = httpResponse.getEntity();
                if (entity != null)
                {
                    InputStream istream = entity.getContent();
                    BufferedReader br = new BufferedReader(new InputStreamReader(istream));

                    try
                    {
                        result = br.readLine();
                    }
                    catch (Exception e)
                    {
                        //TODO Handle the IOException that the readline may throw 
                    }
                    finally
                    {
                        istream.close();
                    }
                }

            }catch (Exception e)
            {
                //TODO Handle the IOException and the ClientProtocolException that the 
                // httpClient.execute can throw
            }
            finally
            {
                httpClient.getConnectionManager().shutdown();
            }
            return result;
        } 

        @Override
        protected void onPostExecute(String result)
        {
            if (result == null)
            {
                tv.setText("The result is NULL");
            }
            else
            {
                tv.setText(result);
            }
        }       
    }
}

Your help is appreceiated,

thanks

like image 922
Lefteris Avatar asked Aug 27 '12 08:08

Lefteris


People also ask

How to call AsyncTask in android?

To start an AsyncTask the following snippet must be present in the MainActivity class : MyTask myTask = new MyTask(); myTask. execute(); In the above snippet we've used a sample classname that extends AsyncTask and execute method is used to start the background thread.

What is AsyncTask explain it in detail?

An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread. An asynchronous task is defined by 3 generic types, called Params , Progress and Result , and 4 steps, called onPreExecute , doInBackground , onProgressUpdate and onPostExecute .

Is Async task deprecated?

AsyncTask is used to perform time talking operations in android, but it's marked as deprecated from android 11. There are many alternatives are available for replacing an AsyncTask, one of the replacements is ExecutorService.

When to use AsyncTask?

For asyncTask when you need something to be returned from a background work, or want to wait for some process to finish before executing some other process or update some view etc.


1 Answers

Instead of doInBackground(), simply call the execute() method of the AsyncTask. Calling doInBackground() does what it says on the tin: calls doInBackground() (in the same thread) and returns. It won't call onPostExecute() for you. execute() will start a background thread, call doInBackground() on the background thread, then post the result of doInBackground() to onPostExecute() on the UI thread.

like image 93
Tamás Avatar answered Sep 23 '22 09:09

Tamás