Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 of this service I am getting compiler error of, "cannot make a static reference to the non static method"

how to fix this?, how I am using the code is shown here;

     @Override
public void run() {
   // I tried both ClientPlayer.runOnUiThread and LotteryServer.runOnUiThread
   // both don't work   
    ClientPlayer.runOnUiThread(new Runnable() {
        public void run() {
           Toast.makeText(getApplicationContext(), "from inside thread", Toast.LENGTH_SHORT).show();
        }
    });
} // end run method
like image 438
Kevik Avatar asked Feb 21 '13 07:02

Kevik


3 Answers

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() {
                    public void run() {
                        tv.setText(fns);///do what
                                    }
                                });

hope it work.

like image 136
Syeda Zunaira Avatar answered Oct 31 '22 08:10

Syeda Zunaira


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.

ClientPlayer extends Activity {
.
.
public static Handler UIHandler;

static 
{
    UIHandler = new Handler(Looper.getMainLooper());
}
public static void runOnUI(Runnable runnable) {
    UIHandler.post(runnable);
}
.
.
.
}

Now u can use this anywhere.

@Override
public void run() {
   // I tried both ClientPlayer.runOnUiThread and LotteryServer.runOnUiThread
   // both don't work   
    ClientPlayer.runOnUI(new Runnable() {
        public void run() {
           Toast.makeText(getApplicationContext(), "from inside thread", Toast.LENGTH_SHORT).show();
        }
    });
} // end run method
like image 20
Vivek Khandelwal Avatar answered Oct 31 '22 06:10

Vivek Khandelwal


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( ...
like image 5
Alex Gittemeier Avatar answered Oct 31 '22 07:10

Alex Gittemeier