Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asynctask Error Handling

I am using AsyncTask to perform some background calculations but I am unable to find a correct way to handle exceptions. Currently I am using the following code:

private class MyTask extends AsyncTask<String, Void, String>
{
    private int e = 0;

    @Override
    protected String doInBackground(String... params)
    {
        try
        {
            URL url = new URL("http://www.example.com/");
        }
        catch (MalformedURLException e)
        {
            e = 1;
        }

        // Other code here...

        return null;
    }

    @Override
    protected void onPostExecute(String result)
    {
        if (e == 1)
            Log.i("Some Tag", "An error occurred.");

        // Perform post processing here...
    }
}

I believe that the variable e maye be written/accessed by both the main and worker thread. As I know that onPostExecute() will only be run after doInBackround() has finished, can I omit any synchronization?

Is this bad code? Is there an agreed or correct way to handle exceptions in an AsyncTask?

like image 553
Leo Avatar asked Sep 11 '10 12:09

Leo


People also ask

Is AsyncTask deprecated?

This class was deprecated in API level 30. AsyncTask was intended to enable proper and easy use of the UI thread. However, the most common use case was for integrating into UI, and that would cause Context leaks, missed callbacks, or crashes on configuration changes.

What are the problems in AsyncTask?

In summary, the three most common issues with AsyncTask are: Memory leaks. Cancellation of background work. Computational cost.

How can we overcome the AsyncTask limitations?

There are two simple solutions that cover most situations: Either check AsyncTask. isCancelled() on a regular basis during your long-running operation, or keep your Thread interruptible. Either way, when you call AsyncTask. cancel() these methods should prevent your operation from running longer than necessary.

What is AsyncTask explain it in detail?

AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.


1 Answers

I've been doing that in my apps, I guess there is not a better way.

You can also read Mark Murphy answer about it.

like image 74
Macarse Avatar answered Oct 19 '22 04:10

Macarse