javaandroidandroid-loader

Setting Properties of ListView Objects in onCreateLoader() Method


I am using a SimpleCursorAdapter to populate a ListView. I am retrieving the following two values from a sqlite Database: name and activated. In my Row ListView, I have a ToggleButton named alarm_activated. In the onCreateLoader() Method, I would like to set the setChecked() to true when the value in the Database is 1, otherwise set the setChecked value to false. Furthermore, I would like to change the background color of the ToggleButton in the same onCreateLoader() Method. I have developed the following code for retrieving the values, which is working properly.

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

    mydb = new DBHelper(this);

    Cursor cursor = getContentResolver().query(CONTENT_URI, null, null, null, "name, activated");

    alarmlv = (ListView)findViewById(R.id.listViewAlarms);

    dataAdapter = new SimpleCursorAdapter(getBaseContext(), R.layout.listview_row, cursor,
            new String[]{ mydb.ALARMS_COLUMN_NAME, mydb.ALARMS_ACTIVATED }, new int[]{ R.id.alarm_name, R.id.alarm_activated}, 0);

    alarmlv.setAdapter(dataAdapter);
    getSupportLoaderManager().initLoader(0, null, this);

}

Meanwhile, I am having difficulties referencing the ToggleButtons in the Row View in order to set their properties as described above. Here is my starting code:

    public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {


    alarm_activated = (ToggleButton)row.findViewById(R.id.alarm_activated);

    if (activationInt == 1) {
        alarm_activated.setChecked(true);
        alarm_activated.getBackground().setColorFilter(Color.BLUE, PorterDuff.Mode.MULTIPLY);
    } else {
        alarm_activated.setChecked(false);
    }


    alarm_activated.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {
                buttonView.getBackground().setColorFilter(Color.BLUE, PorterDuff.Mode.MULTIPLY);
            } else {
                buttonView.getBackground().setColorFilter(Color.LTGRAY, PorterDuff.Mode.MULTIPLY);
            }
        }
    });


    return new Loader(this);
 }

Solution

  • You should create a custom adapter which extends SimpleCursorAdapter and use it instead of SimpleCursorAdapter, then override the getView method and get the reference of child elements from there.