`Can't create handler...Looper.prepare()` in inherited Activity

Luke Vo picture Luke Vo · Jul 18, 2011 · Viewed 8.2k times · Source

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!

Answer

Onuray Sahin picture Onuray Sahin · Jul 18, 2011

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.