harshal harshal - 6 months ago 46
Android Question

Android App crashes after calling finish

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().



Answer Source

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())
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download