1

I'm trying to implement a piece of code I found to store the state of a CheckBox that is in a ListView but it didn't worked. Does anyone have any idea why my code from my adapter isn't working?

package kevin.erica.box;

import java.util.ArrayList;

import kevin.erica.box.R;

import android.R.color;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;

public class MobileArrayAdapter extends ArrayAdapter<String> {
    private final Context context;
    private final String[] values;
    private ArrayList<Boolean> itemChecked = new ArrayList<Boolean>();

    public MobileArrayAdapter(Context context, String[] values) {
        super(context, R.layout.list_adapter, values);
        this.context = context;
        this.values = values;

        for (int i = 0; i < this.getCount(); i++) {
            itemChecked.add(i, false); // initializes all items value with false
        }
    }


    @Override
    public View getView(final int position, View covertView, ViewGroup parent) {
        LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View rowView = inflater.inflate(R.layout.list_adapter, parent, false);
            CheckBox textView = (CheckBox) rowView.findViewById(R.id.checkBox1);
            textView.setTextColor(0xFFFFFFFF);
            textView.setText(values[position]);
            //Store state attempt
            final CheckBox cBox = (CheckBox) rowView.findViewById(R.id.checkBox1); // your
            // CheckBox
            cBox.setOnClickListener(new OnClickListener() {

                public void onClick(View v) {

                CheckBox cb = (CheckBox) v.findViewById(R.id.checkBox1);

                if (cb.isChecked()) {
                    itemChecked.set(position, true);
                    // do some operations here
                } else if (!cb.isChecked()) {
                    itemChecked.set(position, false);
                    // do some operations here
                }
            }
        });
        cBox.setChecked(itemChecked.get(position)); // this will Check or Uncheck the
        // CheckBox in ListView
        // according to their original
        // position and CheckBox never
        // loss his State when you
        // Scroll the List Items.
        return rowView;
    }
}
user
  • 86,916
  • 18
  • 197
  • 190
CarbonAssassin
  • 855
  • 12
  • 24

2 Answers2

2

You question didn't say anything about storing the data after the application has closed. To store the checked CheckBoxes you could use a database or a simple file. Bellow is an example of storing the CheckBox state in a database:

public class SimplePlay extends ListActivity {

    private String[] soundnames;
    private Helper mHelper = new Helper(this, "position_status.db", null, 1);
    private SQLiteDatabase statusDb;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // this is to simulate data
        soundnames = new String[40];
        for (int i = 0; i < 40; i++) {
            soundnames[i] = "Sound " + i;
        }
        // Retrieve the list of position that are checked(if any) from the
        // database
        statusDb = mHelper.getWritableDatabase();
        Cursor statusCursor = statusDb.rawQuery("SELECT * FROM status", null);
        int[] savedStatus = null;
        if ((statusCursor != null) & (statusCursor.moveToFirst())) {
            savedStatus = new int[statusCursor.getCount()];
            int i = 0;
            do {
                savedStatus[i] = statusCursor.getInt(0);
                i++;
            } while (statusCursor.moveToNext());
        }
        // if the cursor is null or empty we just pass the null savedStatus to
        // the adapter constructor and let it handle(setting all the CheckBoxes
        // to unchecked)
        setListAdapter(new MobileArrayAdapter(this, soundnames, savedStatus));
    }

    public class MobileArrayAdapter extends ArrayAdapter<String> {
        private final Context context;
        private final String[] values;
        private ArrayList<Boolean> itemChecked = new ArrayList<Boolean>();

        public MobileArrayAdapter(Context context, String[] values,
                int[] oldStatus) {
            super(context, R.layout.adapters_simpleplay_row, values);
            this.context = context;
            this.values = values;

            // make every CheckBox unchecked and then loop through oldStatus(if
            // not null)
            for (int i = 0; i < this.getCount(); i++) {
                itemChecked.add(i, false);
            }
            if (oldStatus != null) {
                for (int j = 0; j < oldStatus.length; j++) {
                    itemChecked.set(oldStatus[j], true);
                }
            }
        }

        @Override
        public View getView(final int position, View convertView,
                ViewGroup parent) {
            View rowView = convertView;
            if (rowView == null) {
                LayoutInflater inflater = (LayoutInflater) context
                        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                rowView = inflater.inflate(R.layout.adapters_simpleplay_row,
                        parent, false);
            }
            CheckBox cBox = (CheckBox) rowView.findViewById(R.id.checkBox1);
            cBox.setTextColor(0xFFFFFFFF);
            cBox.setText(values[position]);
            cBox.setTag(new Integer(position));
            cBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {

                @Override
                public void onCheckedChanged(CompoundButton buttonView,
                        boolean isChecked) {
                    int realPosition = (Integer) buttonView.getTag();
                    if (isChecked) {
                        itemChecked.set(realPosition, true);
                        // update the database to store the new checked item:
                        ContentValues cv = new ContentValues();
                        cv.put("list_position", realPosition);
                        statusDb.insert("status", null, cv);
                    } else {
                        itemChecked.set(realPosition, false);
                        // delete this position from the database because it was
                        // unchecked
                        statusDb.delete("status", "list_position = "
                                + realPosition, null);
                    }
                }
            });
            cBox.setChecked(itemChecked.get(position));
            return rowView;
        }
    }

    //for working with the database
    private class Helper extends SQLiteOpenHelper {

        public Helper(Context context, String name, CursorFactory factory,
                int version) {
            super(context, name, factory, version);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            // the list_position will hold the position from the list that are
            // currently checked
            String sql = "CREATE TABLE status (list_position INTEGER);";
            db.execSQL(sql);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            // Just for interface
        }

    }

}

After a quick test, the code works. It is just an example.

user
  • 86,916
  • 18
  • 197
  • 190
  • This still isnt storing if the checkbox is checked or not – CarbonAssassin Apr 23 '12 at 16:32
  • @user1337110 How exactly it isn't storing the `CheckBox` state? I tested my code and if you scroll the `ListView` up or down the `CheckBoxes` stay how you check them. – user Apr 23 '12 at 16:38
  • I would like it to store the state of the checkbox once the listview has been closed and once the application has been closed aswell. So next time the application is run it has certian items checked. I think you misunderstood what i wanted – CarbonAssassin Apr 23 '12 at 16:56
  • @user1337110 Your question didn't say that, anyway I've edited my answer and posted an example that will store the `CheckBoxes` status using a database. – user Apr 23 '12 at 17:49
0

you can do one thing take an boolean array of same size & store whether it is clicked or not

you can also use another class to store the checked state...

this is the example of multiple selection of contacts this surely helps u.....

Multiple selection of Contacts

EDIT:

Example

public class simple List extends ListActivity {

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setListAdapter(new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_multiple_choice, GENRES));

    final ListView listView = getListView();

    listView.setItemsCanFocus(false);
    listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
}

private static final String[] GENRES = new String[] { "india", "england", "London", "New york", "New jercy", "LA", "Pakistan", "srilanka", "bangladesh", "chin", "Australia", "Japan" };}
Community
  • 1
  • 1
Wolverine
  • 481
  • 2
  • 10
  • 23