Android Tip: When AsyncTask goes wrong
Every Android developer worth his title knows this problem: you have some long running logic you do not want to run on the main thread, so you offload it to an AsyncTask. The AsyncTask is doing its background work and then, when completed it updates the calling activity.
But hey, the activity might no longer there. It might have been pushed to the background and reclaimed by Android. It might have been recreated due to screen orientation switch. The reason is not important: if you try to update a non-existing activity bad things (read: NullPointerException) will follow.
Now, there are several ways of dealing with this problem, and only one correct way, sometimes called the "weak reference pattern". Let's go over it:
- Before your AsyncTask starts running, keep a weak reference to the calling activity in an AsyncTask member.
- Do your background logic within doInBackground() function
- When its time to update the UI (function onPostExecute) starts by checking the activity weak reference and, if it is null, immediately bail out. Your activity is no longer in existence.
Putting it into code we get:
And no more NullPointerException on user switching the screen.
The WeakReference is of extreme importance here, as it allows the owning activity to be garbage collected by Android. NEVER use this pattern with a "strong" reference to an activity.
Fintech | Payments | Spring-Boot | Backend | Rest | AWS | CI-CD | Docker
8 å¹´Great article, you can add many more thing related to wrong implementation of async task.