Select Checkboxes when click menu item - android

When I press "select all" i want to checked all check boxes which have every listview item it is my layout::
enter code here
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
// Handle item selection
switch (item.getItemId())
{
case R.id.mark_all:
{
CheckBox checkBox = (CheckBox) findViewById(R.id.checkBox);
checkBox.setChecked(true);
return true;
}
default:
return super.onOptionsItemSelected(item);
}
}
this code selects only one checkbox which has first listview item.thank you

Use a for loop to get all the checkboxes
here an example:
boolean check = lv.isItemChecked(0);
for(int i = 0; i <= size; i++)
lv.setItemChecked(i, !check);

use for loop and get the view which contains check box:
for(int i = 0; i < listview.getChildCount(); i++)
{
View v = listview.getChildAt(i);
CheckBox ch = v.findViewById(R.id.checkbox);
ch.setSelected(true);
}

first add SparseBooleanArray in your class
SparseBooleanArray mChecked = new SparseBooleanArray();
now add this function to check:
if check is true than :all item checked
size = no of list vew item
public void setAllChecked(boolean check) {
int size = getCount();
if (check) {
for (int i = 0; i < size; i++) {
mChecked.put(i, true);
notifyDataSetChanged();
}
} else {
for (int i = 0; i < size; i++) {
mChecked.put(i, false);
notifyDataSetChanged();
}
}
now before returning the view check the check box status
CheckbixID.setChecked((mChecked.get(position) == true ? true : false));

Related

check all or uncheck all dynamically created checkboxes in android

1.here all my code.
2.for create dynamic checkbox for check or uncheck all checkboxes
{ final String[][] itemContainer = new String[30][7];
TableLayout tblItemDetail;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_item_code_release);
tblItemDetail = (TableLayout)findViewById(R.id.tblItemDetail);
try {
sqlItem = "";
sqlItem = "SELECT * from itm_mst";
rs = objDbConnect.getResultSet(sqlItem);
if (rs.next()) {
int i1 = 1;
do {
itemContainer[itemCount][0]=Integer.toString(i1++);
itemContainer[itemCount][6]="N"; //checkbox value
itemCount++;
} while (rs.next());
tblItemDetail.removeAllViews();
if (itemCount > 0) {
CheckBox tvchkall = new CheckBox(ItemCodeRelease.this); //header row checkbox for ckeck or uncheck all checkbox
tvchkall.setGravity(Gravity.CENTER);
tvchkall.setPadding(20, 0, 20, 0);
tvchkall.setText("Y");
headerRow1.addView(tvchkall);
tvchkall.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
if(buttonView.isChecked())
{
for(int a = 0 ; a < itemContainer.length ; a++)
{
for(int b = 0 ; b < itemContainer[a].length ; b++)
{
CheckBox chkb = (CheckBox)tblItemDetail.findViewById(a);
if ( chkb == null )
continue;
chkb.setChecked(true);
Log.i("Checkbox serrch","checked "+chkb.getText()+"ID +chkb.getId());
if(a == chkb.getId())
{
itemContainer[a][6] = "Y";
}
else
{
Log.i("Checkbox serrch","unchecked"+chkb.getText()+"ID "+chkb.getId());
itemContainer[a][6] = "N";
}}}}
});
tblItemDetail.addView(headerRow1);
int alternateRow1 = 0;
for (i = 0; i < itemCount; i++) {
TableRow bodyRow1 = new TableRow(ItemCodeRelease.this);
if (alternateRow1 % 2 == 0) {
bodyRow1.setBackgroundResource(R.color.statusalternateRow);
}
else {
bodyRow1.setBackgroundResource(R.color.statusRow);
}
final CheckBox cb1 = new CheckBox(ItemCodeRelease.this); //body row of checkbox
cb1.setId(i);
cb1.setGravity(Gravity.CENTER);
cb1.setPadding(20, 0, 20, 0);
bodyRow1.addView(cb1);
cb1.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
for(int a = 0 ; a < itemContainer.length ; a++)
{
for(int b = 0 ; b < itemContainer[a].length ; b++)
{
if(buttonView.isChecked())
{
Log.i("Checkbox serrch","checked "+buttonView.getText()+"ID "+buttonView.getId());
if(a == buttonView.getId())
{
itemContainer[a][6] = "Y";
continue;
}}
else
{
itemContainer[a][6] = "N";
}}}}
});
bodyRow1.addView(tvBodySRNo1);
tblItemDetail.addView(bodyRow1);
alternateRow1++;
}}}
} catch (Exception e) { e.printStackTrace(); }}
Update [26-01-2016] : You can follow this to Check/UnCheck Dynamically created CheckBoxes.
Inside onCreate(Bundle bundle) { ... } add this :
Few Notes :
You need to give the Base Layout an ID if you use:
setContentView(R.layout.new_layout);
That is, when you set ContentView using layout xml.
You may need to create dummy ids in ids.xml in values folder for usability.
Please keep in mind that you can apply a similar logic for Layout created dynamically instead of using layout xml.
Please keep in mind that you can use similar logic for other Compound Buttons instead of CheckBox.
//Get Base Layout
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.base_layout);
//Create new CheckBox
CheckBox mainCheckBox = new CheckBox(this);
//Create a new ids.xml in values folder and add dummy id there. Than use that dummy id for dynamically created views
mainCheckBox.setId(R.id.main_cb);
//Give a name to it
mainCheckBox.setText(R.string.mainCB);
//Add it to Base layout
linearLayout.addView(mainCheckBox, 0);
//Create other CheckBoxes...
CheckBox[] checkBoxes = new CheckBox[5];
for (int i = 0; i < 5; i++) {
checkBoxes[i] = new CheckBox(this);
checkBoxes[i].setText(String.format(Locale.getDefault(), "Child CheckBox %d", i + 1));
checkBoxes[i].setId(i+101);
linearLayout.addView(checkBoxes[i], i+1);
}
//Creating each checkbox individually:
CheckBox checkBox = new CheckBox(this);
checkBox.setText("Child CheckBox 6");
//Either add an integer value
checkBox.setId(106);
/*
* Or else use a dummy id
* checkBox.setId(R.id.child_cb);
*/
linearLayout.addView(checkBox, 6);
//Set listener to main CheckBox
mainCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//Create an array of integer type to store all ids of child CBs
int[] ids = new int[] { 101, 102, 103, 104, 105, 106 };
/*
* You can also do
* int[] ids = new int[] { 101, 102, 103, 104, 105, R.id.child_cb };
*/
if(isChecked) {
Toast.makeText(getBaseContext(), "Checked", Toast.LENGTH_SHORT).show();
checkChildCBs(ids);
} else {
Toast.makeText(getBaseContext(), "Unchecked", Toast.LENGTH_SHORT).show();
unCheckChildCBs(ids);
}
}
});
Method to check all CheckBoxes
private void checkChildCBs(int[] ids) {
//Create CheckBox array of same size as that of ids
CheckBox[] checkBoxes = new CheckBox[ids.length];
//Run loop to check them
for (int i = 0; i < ids.length; i++) {
checkBoxes[i] = (CheckBox) findViewById(ids[i]);
checkBoxes[i].setChecked(true);
}
}
Method to unCheck all CheckBoxes
private void unCheckChildCBs(int[] ids) {
//Create CheckBox array of same size as that of ids
CheckBox[] checkBoxes = new CheckBox[ids.length];
//Run loop to unCheck them
for (int i = 0; i < ids.length; i++) {
checkBoxes[i] = (CheckBox) findViewById(ids[i]);
checkBoxes[i].setChecked(false);
}
}
/res/values/ids.xml :
<?xml version="1.0" encoding="utf-8"?>
<resources>
<item type="id" name="main_cb" />
<item type="id" name="child_cb" />
</resources>
Update : You can follow the below code to enable/disable Dynamically created CheckBoxPreferences.
Create a new file named preferences.xml in /res/xml/ directory :
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android"
android:key="pref_screen">
</PreferenceScreen>
Than in your PreferenceActivity in onCreate() :
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Add preference xml file from /res/xml/
addPreferencesFromResource(R.xml.preferences);
}
Now we will create CheckBoxPreference dynamically :
// Get PreferenceScreen using the key as stated in preferences.xml
PreferenceScreen prefScreen = (PreferenceScreen) findPreference("pref_screen");
// Now create a CheckBoxPreference array. The size of the array will be the number of required CheckBoxPreferences.
CheckBoxPreference[] cbPrefs = new CheckBoxPreference[5]; // You can set any number you want. This will allow you to create 5 CheckBoxPreferences.
// Run loop to create CheckBoxPreferences and add them to the PreferenceScreen.
for (int i = 0; i < cbPrefs.length; i++) {
cbPrefs[i] = new CheckBoxPreference(getActivity());
cbPrefs[i].setTitle("Dynamically created multiple Pref " + (i+1));
cbPrefs[i].setKey("multiple_dynamic_pref_key_" + (i+1));
prefScreen.addPreference(cbPrefs[i]); // Adds the newly created CheckBoxPreference to the PreferenceScreen
}
/*
IF you want, you can also create new CheckBoxPreference individually like this :
cbPrefs[0] = new CheckBoxPreference(getActivity());
cbPrefs[0].setTitle("My Preference");
cbPrefs[0].setKey("my_pref_key");
prefScreen.addPreference(cbPrefs[0]);
cbPrefs[1] = new CheckBoxPreference(getActivity());
cbPrefs[1].setTitle("Some Name");
cbPrefs[1].setKey("some_pref_key");
prefScreen.addPreference(cbPrefs[1]);
and so on and so forth...
*/
// Now create and add a Preference to the PreferenceScreen
Preference preference = new Preference(getActivity());
preference.setTitle("Preference");
prefScreen.addPreference(preference);
// Now set onPreferenceClickListener to newly created preference.
preference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
String[] prefKeys = new String[] {"multiple_dynamic_pref_key_1", "multiple_dynamic_pref_key_2",
"multiple_dynamic_pref_key_3", "multiple_dynamic_pref_key_4",
"multiple_dynamic_pref_key_5"};
changePrefsState(prefKeys, cbPrefs);
return false;
}
});
Finally your onCreate() will look like this :
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Add preference xml file from /res/xml/
addPreferencesFromResource(R.xml.preferences);
// Get PreferenceScreen using the key as stated in preferences.xml
PreferenceScreen prefScreen = (PreferenceScreen) findPreference("pref_screen");
// Now create a CheckBoxPreference array. The size of the array will be the number of required CheckBoxPreferences.
CheckBoxPreference[] cbPrefs = new CheckBoxPreference[5]; // You can set any number you want. This will allow you to create 5 CheckBoxPreferences.
// Run loop to create CheckBoxPreferences and add them to the PreferenceScreen.
for (int i = 0; i < cbPrefs.length; i++) {
cbPrefs[i] = new CheckBoxPreference(getActivity());
cbPrefs[i].setTitle("Dynamically created multiple Pref " + (i+1));
cbPrefs[i].setKey("multiple_dynamic_pref_key_" + (i+1));
prefScreen.addPreference(cbPrefs[i]); // Adds the newly created CheckBoxPreference to the PreferenceScreen
}
// Now create and add a Preference to the PreferenceScreen
Preference preference = new Preference(getActivity());
preference.setTitle("Preference");
PreferenceScreen.addPreference(preference);
// Now set onPreferenceClickListener to newly created preference.
preference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
String[] prefKeys = new String[] {"multiple_dynamic_pref_key_1", "multiple_dynamic_pref_key_2",
"multiple_dynamic_pref_key_3", "multiple_dynamic_pref_key_4",
"multiple_dynamic_pref_key_5"};
changePrefsState(prefKeys, cbPrefs);
return false;
}
});
}
// This function is called when you click on preference to check/uncheck CheckBoxPrefs.
private void changePrefsState(String[] prefKeys, CheckBoxPreference[] checkBoxPreferences) {
try {
for (int i = 0; i < prefKeys.length; i++) {
checkBoxPreferences[i] = (CheckBoxPreference) findPreference(prefKeys[i]);
// Check if CheckBozPreference is Checked. If yes than unCheck it else Check it
if (checkBoxPreferences[i].isChecked())
checkBoxPreferences[i].setChecked(false);
else
checkBoxPreferences[i].setChecked(true);
}
} catch(Exception e) {
Toast.makeText(getActivity().getBaseContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
}
Old :
private void someFunction() {
String[] prefKeys = new String[] {"pref_key_1", "pref_key_2", "pref_key_3", "pref_key_4", "pref_key_5"};
CheckBoxPreference[] cbPrefs = new CheckBoxPreference[prefKeys.length];
changePrefsState(prefKeys, cbPrefs);
}
private void changePrefsState(String[] prefKeys, CheckBoxPreference[] checkBoxPreferences) {
try {
for (int i = 0; i < prefKeys.length; i++) {
checkBoxPreferences[i] = (CheckBoxPreference) findPreference(prefKeys[i]);
// Check if CheckBozPreference is Checked. If yes than unCheck it else Check it
if (checkBoxPreferences[i].isChecked())
checkBoxPreferences[i].setChecked(false);
else
checkBoxPreferences[i].setChecked(true);
}
} catch(Exception e) {
Toast.makeText(getActivity().getBaseContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
}
The above example works for both Dynamically created preferences and XML defined preferences.
You just need to pass the keys and pref type.
You can make different changePrefsState(arg1, arg2) { ... } for different Preference types.
main checkbox for check all checkbox.
CheckBox tvchkall = new CheckBox(ItemCodeRelease.this);
tvchkall.setId(101);
tvchkall.setOnClickListener(getOnClickDoSomething(tvchkall));
listner that check all checkbox which is dynamicall creater.
View.OnClickListener getOnClickDoSomething(final CheckBox chk) {
return new View.OnClickListener() {
public void onClick(View v) {
if (chk.getId() == 101) {
if (chk.isChecked()) {
for (int a = 1; a < tblItemDetail.getChildCount(); a++) {
itemContainer[a][6] = "Y";
CheckBox cb1 = (CheckBox) ((TableRow) tblItemDetail.getChildAt(a)).getChildAt(1);
cb1.setChecked(true);
}
} else {
for (int a = 1; a < tblItemDetail.getChildCount(); a++) {
itemContainer[a][6] = "N";
CheckBox cb11 = (CheckBox) ((TableRow) tblItemDetail.getChildAt(a)).getChildAt(1);
}
}
} else {
if (chk.isChecked()) {
for (int a = 0; a < itemContainer.length; a++) {
for (int b = 0; b < itemContainer[a].length; b++) {
if (a == chk.getId()) {
itemContainer[a][6] = "Y";
}
}
}
} else {
for (int a = 0; a < itemContainer.length; a++) {
for (int b = 0; b < itemContainer[a].length; b++) {
if (a == chk.getId()) {
itemContainer[a][6] = "N";
}
}
}
}
}
}
};
}

selected check boxes count and passing it to another activity

i have 4 check boxes in 1st activity and i wanna store only those user selected check boxes and have to show in another activity my question is how can i count the user selected checkboxes. please help with me logic
int x = 0;
public void onCheckboxClicked(View view) {
checked = ((CheckBox) view).isChecked();
if (((CheckBox) view).isChecked() == true) {
int i = 0;
while (i != 4) {
x = i + 1;
i++;
}
}
}
On Submit Button
if(x!=0) {
show alert();
and passing check boxes selected count
}
You can run a loop and find the number of CheckBox views and then accordingly get the count of checked CheckBoxes
Ex:
main = (LinearLayout) findViewById(R.id.main);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
count = 0;
int childcount = main.getChildCount();
for (int i=0; i < childcount; i++){
View view = main.getChildAt(i);
if (view instanceof CheckBox) {
if(((CheckBox) view).isChecked())
count++;
}
}
text.setText("count: " + count);
}
});
First put checkboxes in an array:
ArrayList<CheckBox> checkList = new ArrayList<CheckBox>();
you can do it with:
for(int i=0 ; i<4; i++)
{
checkList.add(YOURCHECKBOX) ;
}
than you can check which CB are checked (implement where you want it to save only those which are checked..) with:
for(int i=0 ; i<checkList.size(); i++)
{
if(checkList.get(i).isChecked() == true)
{
YOURCODE
}
}

How to delete multiple selected line items from a listview?

I have implemented a simple method to delete multiple items from a listview following this solution Removing muliple items from listview using Check box in Android, then modified it a small bit to allow for a switch statement for the two button click events, add & delete.But the problem is when I click the delete button the app crashes giving me these errors: http://pastebin.com/2NmCQk2B
I'm not sure why I'm getting the null pointer exception as I believe I have assigned everything correctly.
Can someone better explain why I could be getting this error? Or perhaps a better way of deleting selected line items from a listview?
The complete class is posted below for better understanding:
public class TopRatedFragment extends Fragment implements OnClickListener {
ListView mListView;
EditText mValue;
Button mAdd,mDel;
ArrayList<String> list = new ArrayList<String>();
ArrayAdapter<String> adapter;
SparseBooleanArray mCheckStates ;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_top_rated, container, false);
mAdd = (Button)rootView.findViewById(R.id.newList);
mDel = (Button)rootView.findViewById(R.id.delBtn);
mAdd.setOnClickListener(this);
mDel.setOnClickListener(this);
mValue = (EditText)rootView.findViewById(R.id.listData);
adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_expandable_list_item_1, list);
// set the lv variable to your list in the xml
mListView=(ListView)rootView.findViewById(R.id.listView);
mListView.setAdapter(adapter);
return rootView;
}
public void onClick(View v)
{
switch(v.getId()){
case R.id.newList:
//DO something
String input = mValue.getText().toString();
if(input.length() > 0)
{
// add string to the adapter, not the listview
adapter.add(input);
// no need to call adapter.notifyDataSetChanged(); as it is done by the adapter.add() method
}
break;
case R.id.delBtn:
//DO something
SparseBooleanArray checked = mListView.getCheckedItemPositions();
for (int i = 0; i < mListView.getCount(); i++){
//line 65
if (checked.get(i)==true)
{
list.remove(i);
}
adapter.notifyDataSetChanged();
}
mListView.clearChoices();
}
}
}
You need to use valueAt(), the working code should be
SparseBooleanArray checkedItems = mListView.getCheckedItemPositions();
if (checkedItems != null) {
for (int i=0; i<checkedItems.size(); i++) {
if (checkedItems.valueAt(i)) {
String item = mListView.getAdapter().getItem(
checkedItems.keyAt(i)).toString();
Log.i(TAG,item + " was selected");
}
}
}
Remove from adapter instead from listview try following:
SparseBooleanArray checked = mListView.getCheckedItemPositions();
if(checked!=null){
for (int i = 0; i < mListView.getCount(); i++){
//line 65
if (checked.get(i)==true)
{
adapter.remove(mListView.getItemAtPosition(i));
}
adapter.notifyDataSetChanged();
}
mListView.clearChoices();
}
getCheckedItemPositions Returns:
A SparseBooleanArray which will return true for each call to get(int position) where position is a checked position in the list and false otherwise, or null if the choice mode is set to CHOICE_MODE_NONE.
I used loop this way, and it worked:
SparseBooleanArray checkedItemPositions = getListView().getCheckedItemPositions();
int itemCount = getListView().getCount();
for(int i=itemCount-1; i >= 0; i--){
if(checkedItemPositions.get(i)){
adapter.remove(list.get(i));
}
}
checkedItemPositions.clear();
adapter.notifyDataSetChanged();

android - ListView and ArrayAdapter with simple_list_item_multiple_choice

The following code creates an ArrayAdapter and I change the state of each CheckedTextView using ListView.setItemChecked() in onResume().
This is all fine.
Is there a way I can disable (grey out) some of the CheckedTextViews?
I've tried using adapter.getView(position, null, listView), and while this returns a CheckedTextView object, setting it to setclickable(false) doesn't do anything. I've tried changing its text and changing the state but it doesn't do anything either.
How can I achieve this?
Below is the code that works fine:
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_multiple_choice,
getResources().getStringArray(R.array.mode_declarations_array));
listView.setAdapter(adapter);
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
String learningSettings = settings.getString(Constants.LEARNING_SETTINGS, null);
int count = adapter.getCount();
if (learningSettings != null ) {
String[] values = learningSettings.split(",");
for (int i = 0; i< values.length; i++) {
boolean val = Boolean.parseBoolean(values[i]);
listView.setItemChecked(i, val);
}
}else {
for (int i = 0; i<count; ++i) {
listView.setItemChecked(i, true);
}
}
Create a custom adapter of yours and override the isEnabled function.
class MyAdapter extends ArrayAdapter<String> {
public boolean areAllItemsEnabled() {
return false;
}
public boolean isEnabled(int position) {
// return false if position == position you want to disable
}
}

get all checked item of listview on check of checkbox without using POJO class [duplicate]

I've a couple of question I haven't been able to figure out.
I'm trying to get all the checked elements from a ListView but:
If I check and then uncheck an element, it's returned as "checked" by the getCheckedItemPositions() function
I don't know how can I iterate through this:
SparseBooleanArray checked = list.getCheckedItemPositions();
The other answers using SparseBooleanArray are nearly correct, but they are missing one important thing: SparseBooleanArray.size() will sometimes only return the count of true values. A correct implementation that iterates over all the items of the list is:
SparseBooleanArray checked = list.getCheckedItemPositions();
for (int i = 0; i < list.getAdapter().getCount(); i++) {
if (checked.get(i)) {
// Do something
}
}
I solved my case with this:
public class MyAdapter extends BaseAdapter{
public HashMap<String,String> checked = new HashMap<String,String>();
....
public void setCheckedItem(int item) {
if (checked.containsKey(String.valueOf(item))){
checked.remove(String.valueOf(item));
}
else {
checked.put(String.valueOf(item), String.valueOf(item));
}
}
public HashMap<String, String> getCheckedItems(){
return checked;
}
}
To set an element is checked:
public class FileBrowser extends Activity implements OnClickListener{
private ListView list;
...
list.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int item,
long id) {
BrowserAdapter bla = (BrowserAdapter) parent.getAdapter();
bla.setCheckedItem(item);
}
});
Then to get the checked items from outside the class..
MyAdapter bAdapter;
Iterator<String> it = bAdapter.getCheckedItems().values().iterator();
for (int i=0;i<bAdapter.getCheckedItems().size();i++){
//Do whatever
bAdapter.getItem(Integer.parseInt(it.next());
}
Hope it can help someone.
Jarett's answer is great, but this should be a bit faster, since it's only checking the elements in the sparse array that are present in the underlying array (only those can be true):
SparseBooleanArray checkedItemPositions = listView.getCheckedItemPositions();
final int checkedItemCount = checkedItemPositions.size();
for (int i = 0; i < checkedItemCount; i++) {
int key = checkedItemPositions.keyAt(i);
if (checkedItemPositions.get(key)) {
doSomething(key);
} else {
// item was in the sparse array, but not checked.
}
}
Pro tip: look at the source of SparseBooleanArray, it's a pretty simple class:
http://grepcode.com/file_/repository.grepcode.com/java/ext/com.google.android/android/4.0.3_r1/android/util/SparseBooleanArray.java/?v=source
My brain didn't like looping through the SparseBooleanArray and I didn't need a custom adapter, so the following was a little more intuitive for me:
Don't forget to use CHOICE_MODE_MULTIPLE in onCreate():
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
Use the following method to get an ArrayList of them:
// This example is to get an ArrayList of names (Strings)
protected ArrayList<String> getNames() {
ArrayList<String> names = new ArrayList<String>();
for (int i = 0; i < getListView().getCount(); i++) {
if (getListView().isItemChecked(i)) {
// Do whatever you need to in here to get data from
// the item at index i in the ListView
names.add(mUsers.get(i).getName());
}
}
return names;
}
You can iterate through the SparseBooleanArray using a for loop and the SparseBooleanArray's size() and get(index) methods.
EDIT 3/2/2014: People have pointed out that SparseBooleanArray's size() method returns the number of checked values, rather than the true length of the array, so I have mended my answer to account for that. Essentially it is the same, except that rather than iterating for the length of the array, we iterate until we have found all checked items. Since we only care about the number of checked items, it's irrelevant that with this method, we may not actually get to the end of the array (we won't see anything past the last checked item).
SparseBooleanArray checked = list.getCheckedItemPositions();
int numChecked = checked.size();
for (int i = 0; numChecked > 0; i++){
if (checked.get(i)){
//the item at index i is checked, do something
numChecked--; //We found a checked item, so decrement the number of checked items remaining
}
else
//the item is not checked, do something else
}
final long[] checkedIds = lv.getCheckItemIds();
for (int i = 0; i < checkedIds.length; i++) {
Log.d("checkedIds", "id checked: " + checkedIds[i]);
}
Just saw the question and I was facing the same problem.
There is a simpler solution using SparseBooleanArray to exactly count how many items are checked.
This is my onClick procedure:
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.button:
SparseBooleanArray a = listView.getCheckedItemPositions();
if(checked(vArray)>0) {
String vCheckedList = "";
for (int i = 0; i < nLength; i++) {
if (a.valueAt(i) && i < nLength-1 && a.size()>1)
vCheckedList += listView.getAdapter().getItem(vArray.keyAt(i))+"\n";
else if (a.valueAt(i))
vCheckedList += listView.getAdapter().getItem(vArray.keyAt(i));
}
Toast.makeText(getApplicationContext(), vCheckedList+ " is checked", Toast.LENGTH_SHORT).show();
a.clear();
} else
Toast.makeText(getApplicationContext(), "No Item is Selected", Toast.LENGTH_SHORT).show();
break;
default:
break;
}
}
The checked method:
private int checked(SparseBooleanArray vArray) {
int vCounter = 0;
for(int i=0;i<vArray.size(); i++)
if(vArray.valueAt(i))
vCounter++;
return vCounter;
}
It will solve both problem of the checked items.
I had the same problem and here is my solution with SparseBooleanArray :
SparseBooleanArray checkedPositions = lv.getCheckedItemPositions ();
int size = checkedPositions.size ();
for (int i=0 ; i<size ; i++) {
// We get the key stored at the index 'i'
int key = checkedPositions.keyAt (i);
// We get the boolean value with the key
Log.i (Tag, "checkedPositions(" + key + ")=" + checkedPositions.get (key));
}
In it's entirety this is the solution I used.
Where pos is the Recyclerview item position
SparseBooleanArray selected = new SparseBooleanArray();
//OnClick listener here or whatever you use to check or uncheck an item
if (selected.get(pos, false)) {
selected.delete(pos);
} else {
selected.put(pos, true);
}
selected.size() will reveal how many items are selected
selected.get(pos) will return true if it's selected
The following as has been stated, iterates over all those items which were selected:
for (int i = 0; i < list.getAdapter().getCount(); i++) {
if (selected.get(pos)) {
// Do stuff
}
}
Here is how I get checked items from recyclerview adapter
fun getAllCheckedItems(outList){
for (position in spareBooleanArray.keyIterator()) {
outList.add(mList.get(position)
}
}

Categories

Resources