Skip to content Skip to sidebar Skip to footer

How To Use Runonuithread Without Getting "cannot Make A Static Reference To The Non Static Method" Compiler Error

I have a main class; ClientPlayer extends Activity { and a service LotteryServer extends Service implements Runnable { when trying to use the RunOnUiThread in the run method

Solution 1:

runOnUiThread is not a static method.

If u want to run your runnable on UIThread You can use this

Handler handler = new Handler(Looper.getMainLooper());

This will create a handler for UI Thread.

ClientPlayerextendsActivity {
.
.
publicstaticHandlerUIHandler;

static 
{
    UIHandler = newHandler(Looper.getMainLooper());
}
publicstaticvoidrunOnUI(Runnable runnable) {
    UIHandler.post(runnable);
}
.
.
.
}

Now u can use this anywhere.

@Overridepublicvoidrun() {
   // I tried both ClientPlayer.runOnUiThread and LotteryServer.runOnUiThread// both don't work   ClientPlayer.runOnUI(newRunnable() {
        publicvoidrun() {
           Toast.makeText(getApplicationContext(), "from inside thread", Toast.LENGTH_SHORT).show();
        }
    });
} // end run method

Solution 2:

There is a very simple solution to the above problem just make a static reference of your Activity before your onCreat() method

MainActivity mn;

then initialize it in you onCreat() method like this

mn=MainActivity.this;

and after that you just have to use it to call your runOnUiThread

mn.runOnUiThread(new Runnable() {
                    publicvoidrun() {
                        tv.setText(fns);///do what
                                    }
                                });

hope it work.

Solution 3:

You can get the instance of your Activity, pass it to the service, and use that instead of the class name.

then you can use:

yourActivity.runOnUiThread( ...

Solution 4:

Generally we use this method(RunOnUiThread) when we try to update our UI from a working thread. but As you are Using Service Here, runOnMainThread is seems inappropriate as per your situation.

Better to Use Handler here. Handler is an element associated to the thread where is created, you can post a runnable with your code to the Handler and that runnable will be executed in the thread where the Handler was created.

Create a Handler on your Service in his MainThread and post Runnables on it / send messages to it.

Post a Comment for "How To Use Runonuithread Without Getting "cannot Make A Static Reference To The Non Static Method" Compiler Error"