-1

I can't find a way to use AsyncTask to update the UI

Here's my pseudo-code

public class MissionsActivity extends Activity {

private class UpdateMissions extends AsyncTask<Void, Long, Void> {
    protected Void doInBackground(Void... voids) {
        while(true) {

            try {
                Thread.sleep(250);/
                /*HERE I GET time1, time2, time3 and currentTime READING A FILE*/
                publishProgress(time1,time2,time3,currentTime);
            } catch (Exception e) {

            }
        }
    }

protected void onProgressUpdate(Long time1, Long time2, Long time3, Long currentTime) {
        /*HERE I MANIPOLATE time1, time2, time3 and currentTime TO UPDATE THE UI*/
}

Then in the main class (the one that extends Activity), in the onCreate I do

    update = new UpdateMissions();
    update.execute(null,null,null);

But it does nothing. I'm really hitting a wall here, I need serious help since I never used AsyncTask before.

The while(true) part doesn't let me get to the pre or post execute methods, so I have to use the progress one, but I can't get where the error is.

Thanks in advance

ayyylmao
  • 71
  • 1
  • 13
  • **[How to update ui from asynctask](https://stackoverflow.com/questions/23978400/how-to-update-ui-from-asynctask)** – AskNilesh Feb 20 '18 at 04:30
  • **[Android: How to update an UI from AsyncTask](https://stackoverflow.com/questions/12252654/android-how-to-update-an-ui-from-asynctask-if-asynctask-is-in-a-separate-class)** – AskNilesh Feb 20 '18 at 04:31

3 Answers3

1

Don't forgot to put @Override on required function

Refer answer from: AsyncTask Android example

private class LongOperation extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {
            for (int i = 0; i < 5; i++) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    Thread.interrupted();
                }
            }
            return "Executed";
        }

        @Override
        protected void onPostExecute(String result) {
            // To Modify UI, you need to do it here
        }

        @Override
        protected void onPreExecute() {}

        @Override
        protected void onProgressUpdate(Void... values) {}
    }
Kasnady
  • 2,249
  • 3
  • 25
  • 34
0
while(true) 

part is not stopping you from onPreExecute and onPostExecute . they are still being executed . you just have to override them and update the UI part there .

0

You can't update UI in background, but you can update in onPostExecute() method in AsyncTask

Toe
  • 564
  • 4
  • 11