0

I have a complex class system, with many classes trying to update UI elements, so i searching for most efficient way to achieve this.In my opinion, using handler is the best solution (if you know the better way - please share it ). But there is some problem. If i use this code in separate thread - sended messages seems to be lost(without any warning), and UI handler don't dispatch them:

 Handler handler = new Handler(Looper.getMainLooper());
    Message message = handler.obtainMessage();
    Parameters p = new Parameters(-1, -1);
    p.setObdProtocols(ObdProtocols.values()[protocolPointer]);
    message.obj = p;
    handler.sendMessage(message);

This is code for UI handler:

handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                Log.d("OBD2DEBUGMODE", "MainActivity.handler: handling message: "+msg.what);
                Parameters temp = (Parameters) msg.obj;
                rpmTxt.setText(""+temp.getRpm());
                throtleText.setText(""+temp.getThrotlePosition());
                if(temp.getObdProtocols()!=null) {
                    protoTxt.setText(temp.getObdProtocols().toString());
                }

            }
        };

Above code is not working... Why couldn't i just pass messages to UI thread queue holding reference to UI Looper? How can i update UI thread without passing some objects to background threads?

  • Possible duplicate of [Running code in main thread from another thread](https://stackoverflow.com/questions/11123621/running-code-in-main-thread-from-another-thread) – Iulian Popescu Jan 05 '18 at 11:49
  • Why are you creating another handler when sending the message? Just use the one you created when you implemented `handleMessage`. – Michael Jan 05 '18 at 11:53

0 Answers0