android AsyncTask with activity lifecycle
Asked Answered
T

1

6

Am using AsyncTask in order to download images within my activity

the flow goes like this:

protected void onPreExecute() {
        \\begin animation
}

protected IUpiResponse doInBackground(String... params) {
         \\ download the image
}

protected void onPostExecute(IUpiResponse upiResponse) {
         \\stop the animation
}

till here everything fine, the problem start if i go to background while the asynctask is working sometimes I get an exception nullpointer in the animation stops, because the views no longer valid (i guess),

I can check before the stop animation if the activity is in foreground but i prefer to avoid this approach, what else i can do ?

Terwilliger answered 3/1, 2013 at 12:38 Comment(7)
Did you try it surrund with try {} catch{} ?Meghanmeghann
i agree i can catch this exception, but i prefer to avoid this kind of trickTerwilliger
are you switching to another activity when you come into the onPostExecute()??Photocathode
In that case catch the exception and make print it so you know what is the issue, there you can see what you can make.Meghanmeghann
To little information to give an answer, but keep in mind that an AsyncTask does not run on UI thread, therefore you cannot access/update Views directly from the doInBackground().Intubate
Narendra pal: am not switching any activity AndyRes: am doing update from the pre and post Execute not in doinBackgroundTerwilliger
testing if the view is still visible before stopping an animation on it sound perfectly reasonable to meEtherealize
J
2

I prefer to avoid the asyncTask approach and to download the images in a simple thread, which also saves them to persistence layer such as file system, and then sends an Intent ,

Note: if the activity in the background the Intent ( if you register and unregister your receiver in onResume and onPause as advised ) will not be received so to avoid such cases inside onResume you can check if there is update waiting for you

Judicative answered 3/1, 2013 at 13:3 Comment(1)
This is super cheat / workaround / fake solution.. ;(Farmhouse

© 2022 - 2024 — McMap. All rights reserved.