Dhiraj Choudhary
Dhiraj Choudhary

Reputation: 185

Making CheckBox checked dynamically using setChecked(True)

i have a Listview and each row of listview has a checkbox, now i want to dynamically check or uncheck Checkboxes according to data coming from database, for this i am using checkBox.setChecked(true) method, but checkboxes are not properly checked and unchecked according to data coming from database, please anyone help me. Thanks in advance. Here is My code :

public class Adaptor_CategoryList extends ArrayAdapter<Category> {
public Context mContext;
public ArrayList<Category> listCategory;
public LayoutInflater inflater;
// public OnCheckedChangeListener listnerCheckBox;
public OnCheckedChangeListener listnerCheckBox;

// this arraylist for making checkbox checked and unchecked
public ArrayList<Integer> listCatIds;

public Adaptor_CategoryList(Context context, int resource,
        List<Category> objects, OnCheckedChangeListener listener,
        ArrayList<Integer> listIds) {
    super(context, resource, objects);
    // TODO Auto-generated constructor stub
    mContext = context;
    listCategory = (ArrayList<Category>) objects;
    inflater = (LayoutInflater) mContext
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    listnerCheckBox = listener;
    listCatIds = listIds;

} // constructor ends

public View getView(int position, View convertView, ViewGroup parent) {
    View holder = convertView;
    if (holder == null) {
        holder = inflater.inflate(R.layout.dialog_categorylist, null);
    }
    if (listCategory.size() != 0) {
        TextView txtName = (TextView) holder
                .findViewById(R.id.EditItem_dialogtxtName);
        CheckBox checkCategory = (CheckBox) holder
                .findViewById(R.id.EditItem_dialogCheckBox);
        checkCategory.setTag(position);
        checkCategory.setOnCheckedChangeListener(listnerCheckBox);
        // checkCategory.setOnCheckedChangeListener(listnerCheckBox);
        Category objCategory = listCategory.get(position);
        if (objCategory != null) {
            if (listCatIds.size() > 0) {
                // code for making checkbox checked accroding to item
                // category

                for (int i = 0; i < listCatIds.size(); i++) {
                    int catId = listCatIds.get(i);
                    int id = objCategory.getCatId();

                    if (id == catId) {

                        checkCategory.setChecked(true);

                        System.out
                                .println("checkbox is checked ////// id is  "
                                        + id);
                    } else {
                        checkCategory.setChecked(false);

                    }
                }
            }
            String strName = objCategory.getName();
            if (strName != null) {
                txtName.setText(strName);

            }
        }
    }
    return holder;
}// method ends

} // final class ends

here is my listener defined in other Activty:

CompoundButton.OnCheckedChangeListener listenerCheckBox = new CompoundButton.OnCheckedChangeListener() {

    @Override
    public void onCheckedChanged(CompoundButton buttonView,
            boolean isChecked) {
        // TODO Auto-generated method stub
        try {
            // adding item to category on checkbox checked
            if (isChecked) {
                Object tag = buttonView.getTag();
                if (tag != null) {
                    int position = (Integer) tag;
                    Category objCat = listCategory.get(position);
                    int catId = objCat.getCatId();
                    db.open();
                    long rowId = db.addItemToCategory(itemId, catId);
                    // Toast.makeText(mContext,
                    // "Add Id is"+rowId,Toast.LENGTH_LONG).show();

                    db.close();
                }

            }
            // removing item from category on checkbox unchecked
            else if (!isChecked) {
                Object tag = buttonView.getTag();
                if (tag != null) {
                    int position = (Integer) tag;
                    Category objCat = listCategory.get(position);
                    int catId = objCat.getCatId();
                    db.open();
                    long rowId = db.deleteItemFromCategory(
                            itemId + "".trim(), catId + "".trim());
                    db.close();

                }

            }
        } catch (Exception e) {
            // TODO: handle exception
        }

    }
};

However, this log System.out.println("checkbox is checked ////// id is "+ id); printed on Logcat when if condition satisfies but checkbox do not change its state.please provide me some suggestion.

Upvotes: 0

Views: 1343

Answers (2)

sternze
sternze

Reputation: 1644

this is most likely because you are not updating it on the UI Thread.

Try this:

runOnUiThread(new runnable(){
    public void run(){
        checkCategory.setChecked(true);
    }
});

Upvotes: 0

npace
npace

Reputation: 4258

You have to update the list view so it can reflect the new data. There are two ways you can do this - the first is to call notifyDataSetChanged() on your adapter, which will refresh every recyclable view in the list. It takes exactly one line of code, but it's a bit wasteful and causes unnecessary invalidation and drawing.

The second way is to call your adapter's getView method manually. Here's what I personally do:

    public void updateSingleRow(int position)
{
    // Get the view manually in order to update it, but only if 
    // the position in need of invalidation is visible in the list view.
    if (position >= listView.getFirstVisiblePosition() && position < listView.getLastVisiblePosition())
    {
        View v = ((ViewGroup) listView.getChildAt(listView.getHeaderViewsCount() + (position - listView.getFirstVisiblePosition()))).getChildAt(0);
        adapter.getView(position, v, listView);
    }
}

Upvotes: 1

Related Questions