Android how to runOnUiThread in other class?

49,179

Solution 1

Here's a solution if you don't want to pass the context:

new Handler(Looper.getMainLooper()).post(new Runnable() {
    public void run() {
        // code goes here
    }
});

Solution 2

See the article Communicating with the UI Thread.

With Context in hand, you can create a Handler in any class. Otherwise, you can call Looper.getMainLooper(), either way, you get the Main UI thread.

For example:

class CheckData{
    private final Handler handler;

    public Checkdata(Context context){
       handler = new Handler(context.getMainLooper());
    } 

    public void someMethod() {
       // Do work
       runOnUiThread(new Runnable() {
           @Override
           public void run() {
               // Code to run on UI thread
           }
       });
    }

    private void runOnUiThread(Runnable r) {
       handler.post(r);
    }  
}

Solution 3

Activity is a class that extends Context. So there is no need to pass both context and activity. You may pass activity as context and then you can use the context to run on UI thread as follows:

((Activity) context).runOnUiThread(new Runnable() {
        public void run() {
            //Code goes here
        }
    });

Word of Caution: Only use this when you're sure that context is an activity context, and it's not a good practice to assume that.

Solution 4

class MainActivity extends Activity implements Runnable{

    public void oncreate(){
        new Thread(this).start();
    }

    public void  run(){
        //here is code for download data from server after completion this and in handler  i m call other class in setdata() method....
    }

    public void setdata();
    {
        new checkData(this,MainActivity.this);
    }
}

class checkData{

    public void checkdata(Context context,MainActivity mainactivity){
       mainactivity.runUIonthread()..is works fine for me.....
    }   

}

Solution 5

You might want to take a look at AsyncTask. Even though it's not the best solution, it will help you get started.

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

EDIT

I don't see why using an AsyncTask is not a solution for you but anyway. You can hold a Handler class that is initialized in the UI thread. Then using this Handler you can post back messages to the UI in the form of a runnable. So all you need to do is instantiate a new Handler object when you are in the UI thread (before you start your new one) and then share that with your other class. When you are done, you can use that instance to post a message back to the UI thread using the post method. Check out the documentation of the Handler class for more details:

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

Share:
49,179
Samir Mangroliya
Author by

Samir Mangroliya

10+ years experience as an Android Developer. #Kotlin #Java #Android Experience with Android, Android-SDK, MVVM,LiveData, Android JetPack My Blog: http://samir-mangroliya.blogspot.in/

Updated on February 01, 2020

Comments

  • Samir Mangroliya
    Samir Mangroliya over 4 years

    In my application, in MainActivity, there is a thread which works fine. But when I call another class to get data from the server I can't run on a thread. See code example below.

    class MainActivity extends Activity implements Runnable {
    
        public void onCreate() {
            new Thread(this).start();
        }
    
        public void run() {
            //here is code for download data from server after completion this and in handler  i m call other class in setdata() method....
        }
    
        public void setData() {
            new CheckData(this);
        }
    }
    
    class CheckData {
        public CheckData(Context context) {
            context.runUIonthread(){//cant call as runUIthread............
        }
    }
    
  • Jong
    Jong over 12 years
    AsyncTask wraps the seperated thread and all of its manipulations and implementations in its class, making it much easier for you to use it. Its a very good solution for what you need (Data downloading from a server). You only implement some callback methods, such as when the task is done, before its started and so on... And then you start it from your onCreate method.
  • Samir Mangroliya
    Samir Mangroliya over 12 years
    @Jong i know this very well but i need solution why we cant call runUIthread? so read question carefully........
  • Apparatus
    Apparatus about 11 years
    Have seen your blog post about twitter. Have one doubt. Can you please clarify?
  • Shubham Chaudhary
    Shubham Chaudhary about 9 years
    It is redundant to pass in the activity when you are passing the context. Please look at the solution I shared below stackoverflow.com/a/28873148/2670370.
  • Sipty
    Sipty about 9 years
    how can handler be final without being initialized? :^)
  • Dave T.
    Dave T. almost 9 years
    @Sipty final fields can be initialized in the constructor, as it is in my example
  • The Berga
    The Berga over 8 years
    If you are already passing the context then this is the simplest working solution.
  • hgoebl
    hgoebl almost 8 years
    constructor has no return value. And Java class names should start with capital letter BTW. In spite of having small errors your answer is helpful!
  • Dave T.
    Dave T. almost 8 years
    Also, I was following OP's code, those same mistakes exist, although it's no excuse for me re-posting code with errors.
  • Jaspal
    Jaspal over 4 years
    simplest solution. code for kotlin goes like (context as Activity).runOnUiThread { // code goes here }
  • Sergey Sereda
    Sergey Sereda almost 4 years
    I like this solution but java.lang.ClassCastException: androidx.multidex.MultiDexApplication cannot be cast to android.app.Activity