简体   繁体   中英

Switch State not changing setChecked has no effect

I am working on an App with MQTT Client, on Message Receive I want to change the state of a Switch.

On MQTT messageArrived I have tried to do swLED.setChecked(true); But its not working Has no effect, I mean nothing is changed and also

I don't see next line Log.i(TAG, "DONE"); was executed

and I don't see any exception. Wonder what's happening there!?

swLED.getText() showing the Text of Switch that means swLED is okay here But still swLED.setChecked(true); has no effect

void processMessage(String msg) {
    Log.i(TAG, "Changing Switch Status to ON: "+swLED.getText());
    swLED.setChecked(true);
    Log.i(TAG, "DONE");
}

  //THIS METHOD IS MQTT CLIENT CALL BACK METHOD On Message Recceive  
@Override
public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
    String Message =  new String(mqttMessage.getPayload());
    Log.i(TAG, "messageArrived Topic:" + topic + " Message: " + Message);
    processMessage(Message);
}

public class MainActivity extends AppCompatActivity {
    Switch swLED = null;
    CompoundButton.OnCheckedChangeListener switchListener = new CompoundButton.OnCheckedChangeListener() {

            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    Log.i(TAG, "SWITCH ONNNNNN");
                } else {
                    Log.i(TAG, "SWITCH OFFFFFF");
                }
            }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        swLED = (Switch) findViewById(R.id.swLED);
        swLED.setOnCheckedChangeListener(switchListener);
    }
}

To make changes to UI elements you need to use the runOnUiThread method.

All attempts to update on other threads will throw exceptions which is why you are not seeing the log code run

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM