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............ } }
You need your Activity object to do this. Pass your Activity's this reference through the constructor and use it in your AsyncTask. Since runOnUiThread is a public method in Activity class, you cannot use it in some other Custom class or class that extends other than Activity itself.
Following is a quick code snippet of how to use runOnUiThread () method : Android runOnUiThread Example – In this Android Tutorial, we shall learn how to use runOnUiThread with an Example Android Application. runOnUiThread runs the specified action on the UI thread. If the current thread is the UI thread, then the action is executed immediately.
If you try to touch view of UI thread from another thread, you will get Android CalledFromWrongThreadException. Following is an example Android Application demonstrating the usage of runOnUiThread () method.
UiThreadTest is now supported as part of the core Android test runner to provide the ability to run methods annotated with @Before and @After on the UI thread regardless of what @Test is annotated with. This rule allows the test method annotated with UiThreadTest to execute on the application's main thread (or UI thread).
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.
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 } });
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 you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With