How to uncheck item checked by setItemChecked ()? - android

I am using a ListView with MULTIPLE_CHOICE and to get the selected items back i am using setItemChecked() method.
It works fine as i am able to see the previously checked items.
The issue is that if i uncheck one of the previously checked items, and then get the list of checked items by custList.getCheckItemIds()
the array still has the Item that i unchecked.
Can anyone please tell me if that is supposed to happen or am i missing something?

Here you have to call setOnCheckedChangeListener and you have to manage the code inside this listener block.
checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// Write and manage your code here.
}
});

If you are simply trying to find out what items are checked at any given time, you can get a SparseBooleanArray from the ListView, and iterate over it with a for loop. For example:
SparseBooleanArray checked = list.getCheckedItemPositions();
for (int i = 0; i < checked.size(); i++){
if (checked.get(i))
//the item at index i is checked, do something
else
//the item is not checked, do something else
}

this:
SparseBooleanArray checked = list.getCheckedItemPositions();
for (int i = 0; i < checked.size(); i++){
if (checked.get(i))
//the item at index i is checked, do something
else
//the item is not checked, do something else
}
doens't work.
follow Multiple Contact Picker List [getCheckedItemPositions()]
should be OK.
SparseBooleanArray selectedPositions = listView.getCheckedItemPositions();
for (int i=0; i<selectedPositions.size(); i++) {
if (selectedPositions.get(selectedPositions.keyAt(i)) == true) {
//do stuff
}
}

Related

Onclick of ListView Item, check the checkox?

I have a listview that is built from textviews with the built in Resource Layout simple_list_item_multiple_choice.
syntax like this :
ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_multiple_choice, internet);
If the user clicks an item list, the checkbox of selected item has to be checked.
I know to implement OnItemClickListner, But after it what should I do to check the selected item.
Yu can try this ,referred from https://stackoverflow.com/a/4590897/5193608.
SparseBooleanArray.get returns a boolean, but I believe you need to check it for each position in your list, e.g.
int len = listView.getCount();
SparseBooleanArray checked = listView.getCheckedItemPositions();
for (int i = 0; i < len; i++)
if (checked.get(i)) {
String item = cont_list.get(i);
/* do whatever you want with the checked item */
}

How to get the count of Listview item selection in Android

I have a ListView which am setting that to my adapter. The ListView item contains two view elements which are chekbox and TextView.
I have given the setChoiceMode(ListView.CHOICE_MODE_MULTIPLE) for the ListView.
When i want to select one or more element, I want to get the count (based on selecting and deselecting).
I can't do this stuff in onItemClickListener of ListView.
So I have written the logic in BaseAdapter.
holder.check.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
count += 1;
}
});
But If i deselect the item then the value have to decrease. If iam having only one item in ListView then I can write
SparseBooleanArray checked = listView.getCheckedItemPositions();
and get the value in Fragment. Just I get confused. Could someone help me?
Use this.
SparseBooleanArray checkedItemPositions = getListView().getCheckedItemPositions();
int count = 0;
for (int i = 0, ei = checkedItemPositions.size(); i < ei; i++) {
if (checkedItemPositions.valueAt(i)) {
count++;
}
}
// use count as you wish
Make sure count is in a local (or block of the OnClickListener) scope so that every time you click a button or something, count gets reset and it recounts how many items are checked/unchecked.
Let me know if you have more question :)

Batch delete selected items on ListView/GridView

Following the guide found here http://developer.android.com/guide/topics/ui/menus.html#CAB I went up to a dead end on how to remove all the selected items from the listView's adapter.
In the guide it is shown as a method called deleteSelectedItems(); but since it is never implemented, I got stuck. How can I do this?
I asume you are using a List. Do the following:
private void deleteSelectedItems() {
SparseBooleanArray checked = mListView.getCheckedItemPositions();+
List<YourObject> list = mListOfObjects;
for (int i = 0; i < mListView.getCount(); i++)
if (checked.get(i))
YourObject item = list.get(i);
mListOfObjects.remove(item); //or whatever you want to do with it.
}

Get unchecked items in Listview with MultipleChoice

Sorry for the silly question. I know how to get checked items from ListView (MultipleChoice) with a SparseBooleanArray. But how to get the unchecked items?
Handling the SparseBooleanArray is pretty simple once you get it. If you know which items are checked you should be able to know which items are not checked by making the assumption that all items that are not in the checked positions are unchecked.
SparseBooleanArray checkedPositions = list.getCheckedItemPositions();
for(int i=0; i<myList.size(); i++) {
if(checkedPositions.get(i)) {
// CHECKED
} else {
// NOT CHECKED
}
}

Why is ListView.getCheckedItemPositions() not returning correct values?

The app has a ListView with multiple-selection enabled, in the UI it works as expected. But when I read the values out using this code:
Log.i(TAG,"Entered SearchActivity.saveCategoryChoice()");
SparseBooleanArray checkedPositions = categorySelector.getCheckedItemPositions();
Log.i(TAG,"checkedPositions: " + checkedPositions.size());
if (checkedPositions != null) {
int count = categoriesAdapter.getCount();
for ( int i=0;i<count;i++) {
Log.i(TAG,"Selected items: " + checkedPositions.get(i));
}
}
I get this output, no matter what state each checkbox is in:
Entered SearchActivity.saveCategoryChoice()
checkedPositions: 0
Selected items: false
Selected items: false
Selected items: false
Selected items: false
Selected items: false
Selected items: false
Selected items: false
Selected items: false
Selected items: false
Selected items: false
Selected items: false
Selected items: false
Selected items: false
Selected items: false
Selected items: false
Selected items: false
Selected items: false
The SparseBooleanArray seems to return false for any non-existent item, so the source of the problems seems to be that getCheckedItemPositions() is returning an empty array. The method is behaving as if there are no items in the ListView, but there are.
I can see from the docs that no values are returned when the ListView is not set up as multi-select, but it is, using this statement:
categorySelector.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
In my scenario, the adapter I'm using is a subclass of ArrayAdapter, and (without any solid evidence) I suspect this may be the cause, though I can't see why it shouldn't work.
kcoppock is right, you need to use valueAt(), the working code should be
SparseBooleanArray checkedItems = categorySelector.getCheckedItemPositions();
if (checkedItems != null) {
for (int i=0; i<checkedItems.size(); i++) {
if (checkedItems.valueAt(i)) {
String item = categorySelector.getAdapter().getItem(
checkedItems.keyAt(i)).toString();
Log.i(TAG,item + " was selected");
}
}
}
I remember having an issue with this myself a while back. Here is my previous question, which isn't directly related to your issue, but contains some code that may help. What you might want to try is using checkedPositions.valueAt(int index) rather than checkedPositions.get(int index). I think that may be what you're actually looking for.
I still do not know why, but in my scenario, getCheckedItemPositions() returns false values for all items. I cannot see a way to use the methods on the ListView to get the boolean values out. The SparseBooleanArray object seems to have no real-world data in it. I suspect this may be because of some quirk of my implementation, perhaps that I've subclassed ArrayAdapter. It's frustrating, issues like this are a real time-drain.
Anyway, the solution I have used is to to attach a handler to each Checkbox individually as ListView rows are created. So from ListView.getView() I call this method:
private void addClickHandlerToCheckBox(CheckBox checkbox) {
checkbox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
CheckBox checkbox = (CheckBox)arg0;
boolean isChecked = checkbox.isChecked();
// Store the boolean value somewhere durable
}
});
}
None of the above solutions have worked for me, instead I get every child (a checkedTextView) from the ListView and see if it is checked or not:
ListView myListView = myViewActivity.getListView();
ArrayList<String> selectedChildren2 = new ArrayList<String>();
for(int i = 0;i<myListView.getChildCount();i++)
{
CheckedTextView c = (CheckedTextView) myListView.getChildAt(i);
if(c.isChecked())
{
String child = c.getText().toString();
selectedChildren.add(child);
}
}
It happens if you do not choose the correct resource for showing your different items. It works fine if you choose the built-in resource android.R.layout.simple_list_item_multiple_choice. The method getCheckedItemPositions is coupled in some way to the built-in resource.
There is no need to handle the checking/unchecking of items within the ListView. It already does it on its own.
What does not seem documented is that the ListView will only do this if:
a ListAdapter is set and
the choice mode is CHOICE_MODE_MULTIPLE and
the ids used by the ListAdapter are stable.
The third point was what drove me crazy for a while.
I am not sure what 'stable' means (I guess that the ids don't ever change while the list is displayed).
As far as the ListView is concerned, it means that the method hasStableIds() in ListAdapter returns true.
I created a simple subclass of ArrayAdapter like this:
public class StableArrayAdapter<T> extends ArrayAdapter<T> {
public StableArrayAdapter(Context context, int textViewResourceId, List<T> objects) {
super(context, textViewResourceId, objects);
}
#Override
public boolean hasStableIds() {
return true;
}
}
(You already have your subclass, so just add the hasStableIds override)
Of course, one needs to add the constructor that one was using with ArrayAdapter.
Once you use this class as your ListAdapter, getCheckedItemPositions() behaves as expected.
One last note: setChoiceMode must be called AFTER setting the list adapter.
This is an old thread but since this basically came up first in current Google search here's a quick way to understand what listView.getCheckedItemPositions() does:
Unless the list Item wasn't 'toggled' at all in your ListView, it wont be added to the SparseBooleanArray that is returned by listView.getCheckedItemPositions()
But then, you really don't want your users to click every list item to "properly" add it to the returned SparseBooleanArray right?
Hence you need to combine the usage of valueAt() AND keyAt() of the SparseBooleanArray for this.
SparseBooleanArray checkedArray = listView.getCheckedItemPositions();
ArrayList<DataEntry> entries = baseAdapter.getBackingArray(); //point this to the array of your custom adapter
if (checkedArray != null)
{
for(int i = 0; i < checkedArray.size(); i++)
{
if(checkedArray.valueAt(i)) //valueAt() gets the boolean
entries.yourMethodAtIndex(checkedArray.keyAt(i)); //keyAt() gets the key
}
}
This adjustment fixed it for me.
Change the getView method so that "int position" is "final int position".
Then do this with your checkbox:
((CheckBox) convertView).setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
list.setItemChecked(position, ((CheckBox) buttonView).isChecked());
}
});
Let me elaborate.
list is a reference to the listview and in my case the adapter is an inner class in the dialog holding the list.
I found this thread by having the same problem but I think I have come up with a workaround that worked for me for unkown reasons. Whenever I tried getting a value I got nothing but if I loop through the list setting all to false it started working just like intended.
This was actually a feature I had implemented where the user could either "Select All" or "Unselect All". I run this method in my onCreate.
private void selectNone() {
ListView lv = getListView();
for (int i = 0; i < lv.getCount(); i++) {
lv.setItemChecked(i, false);
}
}
Now all my values are correct. For getting the values, in my case, just Strings.
private void importSelected() {
ListView lv = getListView();
SparseBooleanArray selectedItems = lv.getCheckedItemPositions();
for (int i = 0; i < selectedItems.size(); i++) {
if (selectedItems.get(i)) {
String item = lv.getAdapter().getItem(selectedItems.keyAt(i)).toString();
}
}
selectNone(); //Reset
}
I hope this helps someone.
I too used the solution gyller suggests that involves "initiating" the listview
ListView lv = getListView();
for (int i = 0; i < lv.getCount(); i++) {
lv.setItemChecked(i, false);
}
before calling getCheckItemPositions(), and it stopped producing erroneous results!
while I do not believe I have tried every variation described here, here is the one that has worked for me :)
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
CheckedTextView retView = (CheckedTextView) convertView;
...
retView.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
CheckedTextView chkVw = (CheckedTextView) v;
// chkVw.toggle();
// chkVw.setChecked(!chkVw.isChecked());
mLstVwWordingSets.setItemChecked(position + 1, !chkVw.isChecked());
}
});
...
}
And later
SparseBooleanArray checkedItemsArray = mLstVwWordingSets.getCheckedItemPositions();
for (int i = 1; i < mLstVwWordingSets.getCount(); i++) //skip the header view
{
if (checkedItemsArray.get(i, false))
Log.d(_TAG, "checked item: " + i);
}
I am accessing position + 1 due to a header view that my list has in place.
HTH
ArrayList<Integer> ar_CheckedList = new ArrayList<Integer>();
for each holer of check box i am using to store it in array
holder.chk_Allow.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked)
ar_CheckedList.add(position);
}
});
on click of button
for (int i = 0; i < ar_CheckedList.size(); i++)
{
HashMap<String, String> temp=(HashMap<String, String>) contactList.get(ar_CheckedList.get(i));
str_Phone_No=temp.get(TAG_CONTACT_MOBILE);
send(str_Phone_No);
}
Isn't there a rather fundamental difference between 'selected' and 'checked'?
Suspect you want to setItemChecked() from an OnItemSelectedListener...
simply go to the xml where your listview is defined and set property
**android:choiceMode="multipleChoice"**
my xmlfile
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.ali.myapplication.MainActivity">
<ListView
android:id="#+id/lvCustomList"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:choiceMode="multipleChoice"
/>
</android.support.constraint.ConstraintLayout>
and then in your javafile as:-
SparseBooleanArray checked=lvDetail.getCheckedItemPositions();
for (int i = 0; i < lvDetail.getAdapter().getCount(); i++) {
if (checked.get(i)) {
Toast.makeText(getApplicationContext(),checked.get(i),Toast.LENGTH_SHORT).show();
}
}
ArrayList<String> selectedChildren = new ArrayList<String>();
for(int i = 0;i<list.getChildCount();i++)
{
CheckBox c = (CheckBox) list.getChildAt(i);
if(c.isChecked())
{
String child = c.getText().toString();
selectedChildren.add(child);
}
}
Log.i(TAG, "onClick: " + selectedChildren.size());

Categories

Resources