Wednesday, February 1, 2012

How to get the multiple checked items of Listview in android?


ListView spnAccompanied = (ListView) findViewById(R.id.createactivityplanner_listaccompanied);

//Below we are binding the value present in accompaniedWithArray ArrayList

accompaniedAdapter = new ArrayAdapter<String>(this,R.layout.list_multiple_check, accompaniedWithArray) {
@Override
public View getView(int position, View convertView,
ViewGroup parent) {
View view = super.getView(position, convertView, parent);
TextView chk = (TextView) view.findViewById(android.R.id.text1);
chk.setTypeface(font1);
return view;
}
};
spnAccompanied.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
spnAccompanied.setAdapter(accompaniedAdapter);

//Use below mechanism for retrieving the multiple select checkbox in listview,and seperate it with tild sign

int cntChoice = spnAccompanied.getCount();
SparseBooleanArray sparseBooleanArray = spnAccompanied.getCheckedItemPositions();
for (int i = 0; i < cntChoice; i++) {
if (sparseBooleanArray.get(i)) {
if ("".equals(accompaniedWithID)) {
accompaniedWithID = accompaniedIdArray.get(i).toString()+ "~";
} else {
accompaniedWithID += accompaniedIdArray.get(i).toString()+ "~";
}
}
}
//Remove the last tild in accompaniedWithID
if (accompaniedWithID.length() > 1){
accompaniedWithID = accompaniedWithID.substring(0,accompaniedWithID.length() - 1);
}



OR

Just Call

String [] logs = getCheckedItems();

and create the folowing methods...


private String [] getCheckedItems() {

// Get an array that tells us for each position whether the item is checked or not
 //listView is ListView Object
SparseBooleanArray checkedItems = listView.getCheckedItemPositions();

// For each element in the status array

int checkedItemsCount = checkedItems.size();
System.out.println("checkedItemsCount:"+checkedItemsCount);

String[] log_files = new String [checkedItemsCount];


for (int i = 0; i < checkedItemsCount; ++i) {

// This tells us the item position we are looking at
int position = checkedItems.keyAt(i);

// This tells us the item status at the above position
boolean isChecked = checkedItems.valueAt(i);

   //logsList is array which is binded in the Listview
if (isChecked) {
System.out.println("Checked Logs:"+logsList.get(position));
log_files[i] = absolutePath+"/"+logsList.get(position);
}
}
return log_files;
}




No comments:

Post a Comment