androidandroid-radiobutton

How to set the (checked) state of a radiobutton programmatically in Android?


I have a wireless device with a valve connected to an Android App over Bluetooth LE. In the App I have an activity layout with 2 radioButtons in a radioGroup. On startup, I need to query the external device to determine the current status of the valve and set a radioButton in the App accordingly. My basic strategy is as follows...

private RadioGroup valveStateRadioGroup;
private RadioButton valveOnRadioButton;
private RadioButton valveOffRadioButton;

static boolean valveOn = false;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // set view and init Bluetooth stuff here

    valveStateRadioGroup = (RadioGroup) findViewById(R.id.valve_State_Radio_Group);
    valveOnRadioButton = (RadioButton) findViewById(R.id.valve_on_radioButton);
    valveOffRadioButton = (RadioButton) findViewById(R.id.valve_off_radioButton);

    valveStateRadioGroup.clearCheck();

    valveStateRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener(){
        public void onCheckedChanged(RadioGroup group, int checkedId) {
                // do normal radioButton CLICKED stuff here
        }
    });
    queryValveState(); // call coms routine to get initial device status
}

public void queryValveState() {
    // code here that sends out a wireless query to the device
}

@Override
public synchronized void onDataAvailable(BluetoothGattCharacteristic characteristic) {
    //reply received from device, parse packet, determine valve status
    valveOn = false; // based on reply from device
    refeshUi();
}

private void refeshUi() {
    if (valveOn) {
        valveOnRadioButton.setChecked(true);
    }
    else {
        valveOffRadioButton.setChecked(true); // <<<<<<<<<<<< THIS is the problem
}

The problem I'm having is that when valveOffRadioButton.setChecked(true) fires, it never in turn fires OnCheckedChangeListener nor updates the Widget in the UI. I am able to set the state of the radioButton if I do it in onCreate(). I guess my actual question is... How do you set a radioButton in a routine outside of onCreate()?


Solution

  • Thanks to Muthukrishnan Rajendran for the answer...

    private void refeshUi() {
        runOnUiThread(new Runnable() {
            public void run() {
                if (valveOn) {
                    valveOnRadioButton.setChecked(true);
                }
                else {
                    valveOffRadioButton.setChecked(true);
                }
            }
        });
    }