1

I have a Game Activity (Activity A) that works well with all the code. Then I create a new Activity (Activity B) for my new game mode, that extends Activity A. However, when encounter the Toast line, Activity B suddenly thrown an exception (Activity A works well showing the Toast):

Can't create handler inside thread that has not called Looper.prepare()

Activity B only overrides a load-level method, no any differrence!

Luke Vo
  • 17,859
  • 21
  • 105
  • 181

1 Answers1

9

Try this:

Handler innerHandler;

(new Thread(new Runnable() {

            @Override
            public void run() {
                Looper.prepare();

                innerHandler = new Handler() {
                    @Override
                    public void handleMessage(Message message) {
                        Toast.make(...);
                    }

                    @Override
                    public void dispatchMessage(Message message) {
                        handleMessage(message);
                    }
                };

                Message message = innerHandler.obtainMessage();
                innerHandler.dispatchMessage(message);
                Looper.loop();
            }
        })).start();

There may be an easier way to handle the problem. Please refer to Android – Multithreading in a UI environment documentation.

Onuray Sahin
  • 4,093
  • 4
  • 33
  • 34
  • I struggled with the same problem yesterday. I am happy that helped (: – Onuray Sahin Jul 18 '11 at 12:30
  • @OnuraySahin I know this answer is from a long time ago, but I found it very helpful. However, I am getting a warning at `innerHandler = new Handler()` that says `This Handler class should be static or leaks might occur` However, making it static means that I can't access the context for the Toast. Do you know a way around this? – Deena Aug 07 '14 at 20:06
  • @Deena I think this is a Lint warning. Please try to pass Callback while creating Handler. Like this: innerHandler = new Handler(new Handler.Callback() {... – Onuray Sahin Aug 08 '14 at 08:18
  • @OnuraySahin I tried that, and I'm still getting the same warning. – Deena Aug 09 '14 at 04:57