Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

static method calls Toast.makeText

Tags:

android

I have a thread running in C++, it will call my UI thread's (Java) static method when some condition's satisfied. When the static method was called, I want a Toast to show on my UI. What I have tried are:

1

     static void myMethod(){
        Toast.makeText(context, "message", Toast.LENGTH_SHORT).show();
        (I have a static context reference in global scope)
     }

RESULT:

     E/AndroidRuntime( 1331): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()

2

     static void myMethod(){
         runOnUiThread(new Runnable(){
             public void run(){
                Toast.makeText(Context, "message", Toast.LENGTH_SHORT).show();
             }
         });

RESULT:

   Can not compile: Cannot make a static reference to the non-static method runOnUiThread(Runnable) from the type Activity

Can anybody throw some light on this? Many thanks to you.

like image 330
Eric Lin Avatar asked Sep 21 '11 08:09

Eric Lin


2 Answers

I think you are calling this method from a different thread than the UI thread and this causes an Exception. I have just tried declaring a static method in my Application class that would do the same as your first code. It worked - but of course only when called from main UI thread.

If you would like to be able to call the static method from a different thread, then you will need to create a handler on the UI thread to display the Toast. Something like this:

private static final int MSG_SHOW_TOAST = 1;

private static Handler messageHandler = new Handler() {
       public void handleMessage(android.os.Message msg) {
           if (msg.what == MSG_SHOW_TOAST) {
               String message = (String)msg.obj;
               Toast.makeText(App.this, message , Toast.LENGTH_SHORT).show();
           }
       }
};

private static void displayMessage() {
   Message msg = new Message();
   msg.what = MSG_SHOW_TOAST;
   msg.obj = "Message to show";
   messageHandler.sendMessage(msg);
}

The context in my sample is retrieved from App.this, which is the Application class. You can replace this with your Activity, or your static global context.

like image 66
Daniel Novak Avatar answered Nov 14 '22 16:11

Daniel Novak


static Activity thisActivity = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    thisActivity = this;    
}

public static void showMsg()
{       
  Toast.makeText(thisActivity, "message" , Toast.LENGTH_SHORT).show();
}
like image 37
Javalons Avatar answered Nov 14 '22 15:11

Javalons