Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android's Activity.runOnUiThread is not static, so how can i use it?

For example, if I have a thread doing expensive stuff, and from that thread I want to fire runOnUiThread in the Main (activity) class. Obviously I shouldn't make an instance of my activity class (Main). So if I try

 Main.runOnUiThread(mRunnable);

from my thread it gives me an error saying it's not a static method, and therefor it can't be accessed in my way. Now my understanding would be that the activity class is nearly almost accessed in a static way.
How would I do this?

(Btw: I'm doing this because I was getting CalledFromWrongThreadException, Only the original thread that created a view hierarchy can touch it's views)

like image 614
usealbarazer Avatar asked Dec 16 '22 09:12

usealbarazer


2 Answers

Raunak has the right idea. I'll just add that you can also specify an integer in the method sendEmptyMessage as an identifier to the handler. This will allow you to create one handler that can handle all of your UI updates, e.g.

public static final int EXAMPLE = 0;
public static final int ANOTHER_EXAMPLE = 1;

private final Handler handler = new Handler(){
    @Override
    public void handleMessage(Message msg) {
        switch( msg.what ){
            case EXAMPLE: 
                //Perform action
                break;
            case ANOTHER_EXAMPLE;
                //Perform action
                break;
        }
    }
} 

//Call to submit handler requesting the first action be called
handler.sendEmptyMessage(EXAMPLE);

Hope this helps!

like image 59
Ljdawson Avatar answered May 26 '23 02:05

Ljdawson


You should use the Handler class. The handler class runs on the UI thread. When you finish work in your thread, call handler.sendEmptyMessage(), from where you can make the changes to your ui.

private final Handler handler = new Handler(){
    @Override
    public void handleMessage(Message msg) {
         // make changes to ui
    }
} 
like image 25
Raunak Avatar answered May 26 '23 04:05

Raunak