Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run on UI thread from another class

I searched for a solution and couldn't find one so I'll ask here:

I'm trying to use setText command in the mainActivity, Until now I've used:

 MainActivity.this.runOnUiThread(new Runnable() {
                 public void run() {
                     textViewPrograss.setText(finalI + "");
                 }
             });

now I'm trying to do the same thing, but from another class so i cant use:MainActivity.this.

I was trying to use code i found on another question with no success,This is the code:

new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
    Log.d("UI thread", "I am the UI thread");
}});

Any suggestions?

like image 293
Ben Shabat Avatar asked May 16 '16 09:05

Ben Shabat


2 Answers

You can use this snippet

textView.post(new Runnable() {
        @Override
        public void run() {
            textView.setText("Text");
        }
});
like image 55
user2733760 Avatar answered Sep 19 '22 16:09

user2733760


This (the second code sample from your question) is the correct way to access UI Thread from random location, although you should always try to have a Context to do this :-)

new Handler(Looper.getMainLooper()).post(
    new Runnable() {
        @Override
        public void run() {
            Log.d("UI thread", "I am the UI thread");
    }});

It does work, and if it does not, check if you have debug logs enabled in your debugger ^^

like image 34
Kelevandos Avatar answered Sep 19 '22 16:09

Kelevandos