0

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
    }
}
Gabriella Angelova
  • 2,985
  • 1
  • 17
  • 30
aries
  • 849
  • 3
  • 11
  • 24
  • Maybe yo should call invalidate ? – narancs Jun 22 '15 at 10:29
  • Just update deviceInfo list on click of btnRefresh. – Pavya Jun 22 '15 at 10:47
  • socketSwitch is always the one from last getView call ... you need to fix it: final inside right scope or get/setTag ... of course it will be useless unless you do not save the state somewhere – Selvin Jun 22 '15 at 10:59

1 Answers1

1

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

Sundeep Badhotiya
  • 810
  • 2
  • 9
  • 14