0

I am invoking a method:

method = (MessageController.getInstance()).getClass().getMethod(data.getString("action") + "Action", cArg);
method.invoke(MessageController.getInstance(), "param1");

and the method:

public static void errorAction(String data){
    ProgressDialog dialog = new ProgressDialog(context);
    dialog.setTitle("hi");
    dialog.setMessage("there");
    dialog.show();
}

However i get the following exception:

Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()

on the dialog.show() part.

Is this because of invoking actually happens on a new thread? If yes, how to make it run on UI thread? How to just show the dialog?

Thanks!

Henrique de Sousa
  • 5,727
  • 49
  • 55
Rami Dabain
  • 4,709
  • 12
  • 62
  • 106
  • This answer may help you, it's because the invoking happens on a different thread like you said: [Can't create handler inside thread that has not called Looper.prepare()](http://stackoverflow.com/a/3875204/4368623) – Nahue Aug 25 '16 at 20:44

2 Answers2

0

Or you can run it in the UI thread, like so:

    getActivity().runOnUiThread(new Runnable() {
        @Override
        public void run() {
            method = (MessageController.getInstance()).getClass().getMethod(data.getString("action") + "Action", cArg);
            method.invoke(MessageController.getInstance(), "param1");
        }
    });
Henrique de Sousa
  • 5,727
  • 49
  • 55
0

I'm not exactly sure why you're using reflection to do this, but yes. The reason is you're not on a Looper when invoking the show() method. More likely, you'll get another error if it isn't on the main looper thread (UI thread).

Handlers and Loopers go hand-in-hand. A Looper keeps a thread alive and running and a Handler executes Runnables and posts Messages on that thread.

So, to post to a main thread, you can create a new Handler yourself and pass in the main Looper which will ensure it gets executed on the main thread:

new Handler(Looper.getMainLooper()).post(new Runnable() {
  @Override
  public void run() {
    // Code to execute on the main thread.
  }
}

Doing it this way doesn't require an Activity or View. It will always post on the UI thread and not another Looper thread that you created. Note that this asynchronous and won't execute until the next draw pass.

DeeV
  • 35,865
  • 9
  • 108
  • 95