Android Get Checkbox Info from ListView - android

I have a ListView with multiple checkboxes (one for each list item). What would be the best way to create an array containing information from the selected checkboxes.
For Example, here's a list.
Item 1 "Ham" Checked
Item 2 "Turkey" NotChecked
Item 3 "Bread" Checked
I would like to create an array containing "ham" and "turkey"

If you used ListView's built-in checkbox method with setChoiceMode() then you only need to call getCheckedItemIds() or getCheckedItemPositions().
public class Example extends Activity implements OnClickListener {
ListView mListView;
String[] array = new String[] {"Ham", "Turkey", "Bread"};
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_checked, array);
mListView = (ListView) findViewById(R.id.list);
mListView.setAdapter(adapter);
mListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(this);
}
public void onClick(View view) {
SparseBooleanArray positions = mListView.getCheckedItemPositions();
int size = positions.size();
for(int index = 0; index < size; index++) {
Log.v("Example", "Checked: " + array[positions.keyAt(index)]);
}
}
}
If the Adapter is bound to a Cursor, then this becomes much more practical.

Related

android 2d array to listview

so i've got this piece of code and i want it to output attr1 and attr2 in the listview, but the current error i get is: cannot resolve constructor. Here is the piece of code:
private String[][] content = {
{"attr1", "url1"},
{"atrr2", "url2"}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
ListView lv = (ListView) findViewById(R.id.lv);
for(int i = 0; i < content.length; i++) {
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, content[i][0]);
lv.setAdapter(adapter);
}
}
Hopefully somebody could help me, thanks in advance (sorry for the bad english)
Move the creation of the list outside your for loop like so:
ListView lv = (ListView) findViewById(R.id.lv);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
for(int i = 0; i < content.length; i++) {
adapter.add(content[i][0]);
}
lv.setAdapter(adapter);
You can get the index of the clicked item and use that information to access your array again and get the second piece of information

In android am using multiple choice list for contact selection how to select all contact at one button click

Hi am using multiple choice list
can any one tell me how should i select all
item on any button click event
or how unselect all item on button click event
my code is here
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.contact_list);
findViewsById();
PhoneContacts pc = new PhoneContacts(ContactList.this);
pc.readContacts();
for (int i = 0; i < pc.allPhoneNumbers.size(); i++) {
_allNumberAndNameMergeList.add(pc.allContactName.get(i) + "\n"
+ pc.allPhoneNumbers.get(i));
}
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_multiple_choice,
_allNumberAndNameMergeList);
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
listView.setAdapter(adapter);
button.setOnClickListener(this);
}
private void findViewsById() {
listView = (ListView) findViewById(R.id.list);
button = (Button) findViewById(R.id.testbutton);
}
public void onClick(View v) {
SparseBooleanArray checked = listView.getCheckedItemPositions();
ArrayList<String> selectedItems = new ArrayList<String>();
for (int i = 0; i < checked.size(); i++) {
// Item position in adapter
int position = checked.keyAt(i);
// Add sport if it is checked i.e.) == TRUE!
if (checked.valueAt(i))
selectedItems.add(adapter.getItem(position));
}
String[] outputStrArr = new String[selectedItems.size()];
for (int i = 0; i < selectedItems.size(); i++) {
outputStrArr[i] = selectedItems.get(i);
}
}
}
Hi am using multiple choice list
can any one tell me how should i select all
item on any button click event
or how unselect all item on button click event
I would create custom adapter that extends ArrayAdapter and ListView item that would contain e.g. CheckBox. Than inside adapter class getView() method handle selected items position to get objects on current position and you can do anything you wish. You can have a look at this tutorial - 12. Selecting multiple items in the ListView
http://www.vogella.com/articles/AndroidListView/article.html

Delete multiple selected items in ListView

I have a list view that displays records from a database. Each row in the listview has a checkbox. How do I...
Create a toast message displaying the value of the selected item?
Identify the records selected by the user in the listview?
Iterate through each selected item and delete only the rows selected in the listview from the database?
I've been following this helpful tutorial here: //http://www.vogella.com/articles/AndroidSQLite/article.html
public class PhoneNumberDataBaseListView extends ListActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
NumbersDataSource datasource = new NumbersDataSource(this);
datasource.open();
String number = "123";
datasource.createNumber(number);
List<Number> values = datasource.getAllNumbers();
ArrayAdapter<Number> adapter = new ArrayAdapter<Number>(this, android.R.layout.simple_list_item_multiple_choice, values);
setListAdapter(adapter);
}
public void deleteNumber() {
NumbersDataSource datasource = new NumbersDataSource(this);
datasource.open();
ListView LV = (ListView) findViewById(android.R.id.list);
List<Number> values = datasource.getAllNumbers();
ArrayAdapter<Number> adapter = new ArrayAdapter<Number>(this, android.R.layout.simple_list_item_multiple_choice, values);
setListAdapter(adapter);
SparseBooleanArray checkedItems = LV.getCheckedItemPositions();
for (int i = 0; i < checkedItems.size(); i++) {
if(checkedItems.valueAt(i)) {
Number item = adapter.getItem(i);
Toast t = Toast.makeText(this, item.getNumber().toString(), Toast.LENGTH_LONG);
t.show();
}
}
}
Method getCheckedItemPositions() returns SparseBooleanArray that indicates which items are checked (if item on specific position is checked, method valueAt(position) invoked on that array returns true). Class DBAdapter from tutorial you are following provides you with deleteTitle(long rowId) method which you should use to acheive what you want.Therefore your code should look more or less like this:
SparseBooleanArray checkedItems = listView.getCheckedItemPositions();
for (int i = 0; i < checkedItems.size(); i++) {
if(checkedItems.valueAt(i)) {
db.deleteTitle(adapter.getItemId(i));
}
}
Of course SimpleCursorAdapter and DBAdapter should be stored in object attributes so that you have access to them from both methods (onCreate and deleteRecord). By the way, View parameter passed to deleteRecord method is not needed.

How to add an Array of TextViews into a ListView?

I got this piece of code that creates new TextView, then adds it to ArrayList<View> and when it is finished adding TextViews to Array it sets adds that Array into ListView. But somehow my ListView is appearing empty. Any idea what am I doing wrong?
Here is the code:
ListView lv = (ListView) findViewById(R.id.listView1);
ArrayList<View> textvs = new ArrayList<View>();
for (int i=0; i<10;i++) {
TextView tv = new TextView(MainActivity.this);
tv.setText(""+i);
textvs.add(tv);
}
lv.addTouchables(portit); // lv is my listview
You should use ArrayAdapter. You did this the wrong way. Here is a sample:
public class ArrayAdapterDemo extends ListActivity {
String[] items = { "this", "is", "a", "really", "silly", "list" };
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_expandable_list_item_1,
items));
}

android how to dynamically bind checkboxes with custom listview

I create checkboxes dynamically & i want to bind that checkboxes to listview.
How can I do that?
Here i give my code--
public class HomeActivity extends ListActivity{
CheckBox[] chk;
ListView lv1;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
lv1=(ListView)findViewById(R.id.listTasks);
tv1=(TextView) findViewById(R.id.tvMsg);
The database section:
db = new DBAdapter(HomeActivity.this);
db.open();//int[] id=new int[]{Integer.parseInt(DBAdapter.ID)};
Cursor cr=db.getUncompletedTask();//my database function to retrieve values to create checkboxes
if (cr.moveToFirst()) {
do {
String[] str=new String[2];
str[0]=cr.getString(0);
str[1]=cr.getString(1);
al.add(str);
} while (cr.moveToNext());
}
startManagingCursor(cr);
String[] tasks = new String[] { DBAdapter.KEY_TODO };
Creation of checkbox:
int[] idchk=new int[al.size()];//here i am creating checkbox dynamicaly
if (al.size() != 0) {
chk = new CheckBox[al.size()];
System.out.println(al.size());
for (int i = 0; i < al.size(); i++) {
String[] s = (String[]) al.get(i);
System.out.println("ID: "+s[0]);
Task_Id = Integer.parseInt(s[0]);
Task_Nm = s[1];
chk[i] = new CheckBox(HomeActivity.this);
System.out.println(i +"task id"+Task_Id +"parseint"+Integer.parseInt(s[0]+chk[i].getText().toString()));
chk[i].setId(Task_Id);
idchk[i]=Task_Id;
chk[i].setText(Task_Nm);
//lv1.addView(chk[i]);
//setContentView(lv1);
}}}
Here what can i write here so that this dynamically created checkboxes will be bind to listview
What if you use the default listview of android with checkbox.
By using :
setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_checked, COUNTRIES));
where COUNTRIES is static final string array that contains the item to show..
You can use customized ListView whose rows contains CheckBox. Create your own adapter extending ArrayAdapter and it's overridden method getView create your checkboxes.

Categories

Resources