Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switch State not changing setChecked has no effect

Tags:

android

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);
    }
}
like image 729
Ashok Avatar asked Jan 24 '26 09:01

Ashok


1 Answers

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

like image 140
hardillb Avatar answered Jan 26 '26 00:01

hardillb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!