Unable to change switch state from async task

525 views Asked by At

I need to change the state of the switch from inside an async task. I have set an onClickListner() on the switch in my custom adapter and I am passing its reference to the async task. In my async task I trying to update the state of the switch using publish progress and onProgressUpdate. But the state of the switch is not changing in the UI. Could someone please help me on this?

Below is my code:

DeviceAdapter.java

public class DeviceAdapter extends ArrayAdapter<Device> {

private List<Device> deviceInfo;
private Device device;

private View customView;
private Switch socketSwitch;

private DevicesInfoDbAdapter devicesInfoDbAdapter;

public DeviceAdapter(Context context, List<Device> deviceInfo) {
    super(context, R.layout.row_device_details, deviceInfo);
    this.deviceInfo = deviceInfo;
    device = deviceInfo.get(0);
    devicesInfoDbAdapter = DBFactory.getDevicesInfoDbAdapter(getContext());
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    LayoutInflater layoutInflater = LayoutInflater.from(getContext());
    customView = layoutInflater.inflate(R.layout.row_device_details, parent, false);
    socketSwitch = (Switch) customView.findViewById(R.id.socketSwitch);
    ImageButton btnRefresh = (ImageButton) customView.findViewById(R.id.btnRefresh);


    btnRefresh.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.d("socketswitch1",""+socketSwitch);
            DeviceStatusRefreshAsync deviceStatusRefreshAsync = new DeviceStatusRefreshAsync(socketSwitch);
            deviceStatusRefreshAsync.execute();
        }
    });

    return customView;
}


}

DeviceStatusRefreshAsync.java

public class DeviceStatusRefreshAsync extends AsyncTask {

    private Switch socketSwitch;

    public DeviceStatusRefreshAsync(Switch socketSwitch) {
        this.socketSwitch = socketSwitch;
    }

    @Override
    protected Object doInBackground(Object[] params) {

        publishProgress();  //Calling to update the switch state

        return null;
    }

    @Override
    public void onProgressUpdate(Object[] values) {

        socketSwitch.setChecked(true);   //Switch state not changing in the UI
    }
}
1

There are 1 answers

6
Sundeep Badhotiya On

Instead of using OnClickListener use OnCheckedChangeListener and instead of using onProgressUpdate use onPostExecute for change the state of switch.