0

I am calling a Handler class from a background thread. In the Handler class, I am trying to display a toast. Theoratically it should work flawlessly because Handler is the Queue that forwards the UI tasks to the main UI thread. However, in my case the I am getting exception.

private void firstTimeLogin() {

        final LoginUiThreadHandler loginHandler = new LoginUiThreadHandler();

        new Thread(new Runnable() {
            @Override
            public void run() {
                Message m = loginHandler.obtainMessage();

                Bundle bund = new Bundle();
                bund.putInt("loginResult", 1);
                m.setData(bund);

                loginHandler.handleMessage(m);
            }
        }).start();
    }

    private class LoginUiThreadHandler extends Handler {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            int loginResult = msg.getData().getInt("loginResult");
            if(loginResult == 0) 
                Toast.makeText(getActivity().getApplicationContext(), "Login success", Toast.LENGTH_SHORT).show();

        }
    }

What am I doing wrong?

user2498079
  • 2,872
  • 8
  • 32
  • 60

1 Answers1

-1

Replace with -

LoginUiThreadHandler loginHandler = new LoginUiThreadHandler(Looper.getMainLooper());

instead of-

LoginUiThreadHandler loginHandler = new LoginUiThreadHandler();

Shahzadah
  • 49
  • 5
  • Then, you need to create constructor in LoginUIThreadHanlder with parameter Looper and pass to super(looper) as- LoginUiThreadHandler(Looper l){ super(l); } – Shahzadah Feb 18 '16 at 09:30