Lincy
Lincy

Reputation: 1093

Doing UI task in doinbackground() in Android

Is there a way to do UI task in the doinbackground() of the AsyncTask. I am well aware it is better to do it in onPostExecute method. But in my case since I am need to use a reusable alert, being able to access the UI in my doinbackground would save me a lot of time. That is, I need to tweak the code in 46 places but being able to do this in the doinbackground will need the change in just one place.

Thanks in advance

Upvotes: 8

Views: 9458

Answers (3)

Sreedev
Sreedev

Reputation: 6653

Hope this will solve your problem

    onPreExecute() {
       // some code #1
    }

    doInBackground() {
        runOnUiThread(new Runnable() {
                    public void run() {
                        // some code #3 (Write your code here to run in UI thread)

                    }
                });
    }

    onPostExecute() {
       // some code #3
    }

Upvotes: 28

Paresh Mayani
Paresh Mayani

Reputation: 128428

Other than updating UI from onPostExecute(), there are 2 ways to update UI:

  1. From doInBackground() by implementing runOnUiThread()
  2. From onProgressUpdate()

FYI,

onProgressUpdate() - Whenever you want to update anything from doInBackground(), You just need to use publishProgress(Progress...) to publish one or more units of progress, it will ping onProgressUpdate() to update on UI thread.

Upvotes: 7

Nezam
Nezam

Reputation: 4132

you could utilize onProgressUpdate rather

Docs

Upvotes: 3

Related Questions