How to do GUI stuff in background? (Android)

58 views Asked by At

I tried to do gui stuff with asynctask, but it not works on every device. Why?

Here is my code:

public class DownloadWebPageTask extends AsyncTask<ReadEvent, Void, String> {

    long difference;
    ReadEvent readevent;

    @Override
    protected String doInBackground(ReadEvent... readevents) {
        this.difference = (readevents[0].getDtstart() - calendar_millis) / 1000 / 24 / 60 / 60;
        this.readevent = readevents[0];

        return "";
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        MonthFragment.this.addDate((int) difference + MonthFragment.this.start - 1, readevent.getEventname(), readevent.getCalendarid(), readevent.getEventcolor());
    }
}

This is within a fragment. The method addDate adds the TextView to GUI. It works great on Honor Huawei 6X Honor (Android 7.0) it works great. On BQ Aquaris X5 (Android 7.1.1) it doesn't.

What is the best way, to do GUI stuff in background?

1

There are 1 answers

7
cab404 On

AsyncTask is rather inconsistent between platforms. Try this in onPostExecute:

if (getView() != null)
    getView().post(new Runnable() {
        public void run() {
            MonthFragment.this.addDate((int) difference + MonthFragment.this.start - 1, readevent.getEventname(), readevent.getCalendarid(), readevent.getEventcolor());
        }
    });

But I'd rather use thread pools, they offer much more control.