1

This was something that I expect not to be happening as per my understanding.

In my app, I execute() an AsyncTask which might take less than 2-3 seconds. In that AsyncTask I have runOnUiThread() which updates few UI controls value.

This works fine until, if I do a click on Sign out button which does a finish() of Activity.

I get Null pointer exception that findViewById returned null. I can add null check before updating but considering the amount of UI screens and AsyncTasks used I would end up in huge number of checks.

Why would the UI thread still be in execution after finish() is called?

What is best solution to this case? Issue happens only when there is exact coincidence with time difference between AsyncTask completion and call to finish().

Regards,

Harsha

harshal
  • 592
  • 6
  • 25
  • 1
    https://stackoverflow.com/questions/31085406/what-happens-to-running-asynctasks-when-the-activity-changes – Daniel Nugent Sep 22 '17 at 21:46
  • 1
    https://stackoverflow.com/questions/2531336/asynctask-wont-stop-even-when-the-activity-has-destroyed – Daniel Nugent Sep 22 '17 at 21:47
  • Daniel, info in those tickets seems to be worth enough enough to give a try..I was searching with different perspective. – harshal Sep 22 '17 at 21:52
  • Daniel, I have another follow up question. Since issue is appearing in code inside runOnUiThread(), If the main thread (UI thread) has got cancelled by OS due to finish() will there be any exception to runOnUiThread() tried to look for UI thread? I am not sure how exactly I can test this to verify. – harshal Sep 22 '17 at 22:01
  • @harshal There will naturally be an NullPointerException thrown when your asyncTask looks for a certain view that it will not find (since your activity was finished, and thus your UI elements are gone) – Husayn Hakeem Sep 22 '17 at 22:06

2 Answers2

1

The AsyncTask runs in the background until the job it's executing is completed, so calling "finish" to the current activity does not kill it. Adding null checks would be a hassle as you said, so instead what I'd do is cancel the asyncTask before calling finish().

if (asyncTaskInstatnce != null && !a.isCancelled())
     a.cancel(true);
Husayn Hakeem
  • 4,184
  • 1
  • 16
  • 31
0

You use the onPostExecute method of the AysncTask to update the UI.

Adrian Le Roy Devezin
  • 672
  • 1
  • 13
  • 41