How to update UI from a Runnable?

12,019

Solution 1

runOnUiThread() requires Activity reference. There are alternatives. You don't need Activity reference to your Thread. You can always get UI handler with the main looper. Pass other arguments like your interface to update the fragment upon completion of your task.

class RequestAccountInfoTask implements Runnable {

    private Account account;
    private Handler mHandler;
    public RequestAccountInfoTask(Account account) {
        this.account = account;
        mHandler = new Handler(Looper.getMainLooper());
    }

    @Override
    public void run() {
        doRequestAccountInfo(account);
        //use the handler
    }
}

Anything you run on the instantiated Handler will be on UI thread.

Of course, using runOnUiThread() is totally reasonable.

Solution 2

you can use runOnUIThread method of activity.

here's code may be help you:

class RequestAccountInfoTask implements Runnable {

    private Account account;

    public RequestAccountInfoTask(Account account) {
        this.account = account;
    }

    @Override
    public void run() {
        doRequestAccountInfo(account);
        if (getActivity() != null) {
            getActivity().runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    // you can update fragment UI at here
                }
            });
        }
    }
}

Solution 3

Please take a look at AsyncTask for updating the UI from a thread:

http://developer.android.com/reference/android/os/AsyncTask.html

Here are the highlights from the above link:

Class Overview AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.

AsyncTask is designed to be a helper class around Thread and Handler and does not constitute a generic threading framework. AsyncTasks should ideally be used for short operations (a few seconds at the most.) If you need to keep threads running for long periods of time, it is highly recommended you use the various APIs provided by the java.util.concurrent package such as Executor, ThreadPoolExecutor and FutureTask.

An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread. An asynchronous task is defined by 3 generic types, called Params, Progress and Result, and 4 steps, called onPreExecute, doInBackground, onProgressUpdate and onPostExecute.

Solution 4

You Cannot Update UI from runnable. You Need Handler for Updating UI. See this for more info.

Solution 5

The UI only can be modified by the thread that create it. In tho most cases is by the UI thread. So you need yo update using runOnUiThread method. Good Luck

Share:
12,019
Logan Guo
Author by

Logan Guo

android developer

Updated on June 14, 2022

Comments

  • Logan Guo
    Logan Guo almost 2 years

    I need to update ui from runnable. My logic goes like below. I start the runnable from onCreate of the fragment lifecycle. And the runnable instance is responsible to request network. The problem is I don`t know how to update the fragment after runnable instance fetched the data from network.

    code to start runnable in fragment in CustomFragment.java.

    public void onCreate(Bundle savedInstanceState) {
        Log.d(DEBUG_TAG, "onCreate");
        super.onCreate(savedInstanceState);
    
        accountMgr.requestAccountInfo();
    
    }
    

    code to start runnable in AccountManager.java

    /**
     * request Account info from server
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public void requestAccountInfo() {
        Account act = getCurrentAccount();
        Thread t = new Thread(new RequestAccountInfoTask(act));
        t.start();
    }
    
    /**
     * automatically update Account info, like space usage, total space size, from background.
     */
     class RequestAccountInfoTask implements Runnable {
    
        private Account account;
    
        public RequestAccountInfoTask(Account account) {
            this.account = account;
        }
    
        @Override
        public void run() {
            doRequestAccountInfo(account);
    
        }
    }
    
  • Logan Guo
    Logan Guo over 9 years
    I have implemented this comment, some reference here
  • Cameron Lowell Palmer
    Cameron Lowell Palmer about 7 years
    This example right off Google's own pages is a runnable calling the UIThread. developer.android.com/guide/components/…