Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The method runOnUiThread(Runnable) in the type Activity is not applicable for the arguments (void)

I am trying to create a dialog from a non-UI thread, in onUtteranceCompleted():

runOnUiThread(
    new Thread(new Runnable() {
      public void run() { MyDialog.Prompt(this); }
    }).start());

Prompt() is a simple static method of the class MyDialog:

  static public void Prompt(Activity activity) {
    MyDialog myDialog = new MyDialog();
    myDialog.showAlert("Alert", activity);     
  }

The problem is that I cam getting two errors for what I am trying to do:

  1. The method runOnUiThread(Runnable) in the type Activity is not applicable for the arguments (void)
  2. The method Prompt(Activity) in the type MyDialog is not applicable for the arguments (new Runnable(){})

All I wanted is "do it right" by deferring dialog creation to a UI thread, but it appears that I am missing something fundamental.

What am I missing and how do I accomplish the seemingly simple task that I am trying to achieve?

like image 733
an00b Avatar asked Dec 21 '22 16:12

an00b


1 Answers

It must be:

runOnUiThread(new Runnable() {
      public void run() { MyDialog.Prompt(NameOfYourActivity.this); }
    });

It says that is not applicable for the arguments (void) because you are trying to run a thread using the start method (which is a void method). runOnUiThread receives a runnable object, and you don't have to worry about starting it, that's done by the OS for you.

With regards to the second error, it happens because in that scope this is referring to the Runnable object that you are initializing, rather than the reference to the activity. So, you have to explicitly tell what this you are referring to (in this case YourActivityName.this).

like image 151
Cristian Avatar answered Dec 28 '22 07:12

Cristian