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 exampl
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);
}
}
If someone's looking for an Rx based solution:
Observable.just(true)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(aBoolean -> {
// cool stuff comes here
});
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
}
});
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.
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.....
}
}
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