Android how to runOnUiThread in other class?

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............
    }
}

Solution 1:

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 2:

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 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.....
    }   

}