Why my listview only detects the first checkbox? - android

i got a problem with my listview. basically consists of a list generated from a search in database, but when loading the list, only detects the first checkbox as checked or unchecked, ignoring the rest.
the code is this:
public void AnyadirProdLista() {
// TODO Auto-generated method stub
ListView lista = (ListView) view.findViewById(R.id.ListaProds);
CheckBox check = (CheckBox) view.findViewById(R.id.checkLista);
int contador = lista.getCount();
for (int i = 0; i < contador; i++){
if (check.isChecked()){
Toast.makeText(getActivity(), "a" + i, Toast.LENGTH_LONG).show();
}
}
}
when i do this and click the button that activate this method, only if the first check box of the list ( the 0 position item in the list ) makes work the toast and do it all the loop, but the other checkbox do nothing.
I do focusable false the checkbox in the view, and don't know nothing more to do, if someone can help me i will be very thankful.

CheckBox check = (CheckBox) view.findViewById(R.id.checkLista);
you get one check box and you only check the one you got above
if (check.isChecked()){
Toast.makeText(getActivity(), "a" + i, Toast.LENGTH_LONG).show();
}
while you iterate throw your list you should overwrite "check" with an other checkbox

Related

How to check if checkbox is checked in a specific row?

I generated a table which has checkboxes at the end of every row. I want to sum all of values in the specific row if the checkbox is selected in that row. Therefore I need to check if the checkbox is checked in that specific row. So far I have this:
btnCalculate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
int sum = 0;
for(int i=0; i<rowNumber; i++) {
if(cb.isChecked()) {
sum = sum + rowSums[i];
}
}
txtResult.setText(String.valueOf(sum));
} catch (Exception e) { }
}
});
Normally, I can access the values of all cells withing a row and I am able to sum all of those values inside the row. However, when I add if statement inside the sum, I always get 0. I know what is the problem. I know I have to check if the checkbox is checked in that specific row. But I don't know how to do that.
By the way I also set IDs for every checkboxes inside the row. For example, ID of the first row's checkbox is 0 and the second row's is 1 and so on. So I just have to access that specific checkbox and check if it is checked.
EDIT (SOLVED)
I stored every checkboxes inside a CheckBox array. Then in my for loop, I called that specific CheckBox and it worked fine.
private CheckBox cb;
private CheckBox [] cbs;
In the for loop:
cbs[i] = cb;
And my for loop:
for(int i=0; i<rowNumber; i++) {
if(cbs[i].isChecked()) {
sum = sum + rowSums[i];
}
}
You can create a listener for the checkboxes so that when any checkbox is checked/unchecked add/delete the corresponding data to the calculation.
OR:
You can give all the checkboxes ids, and then store the ids in an array in the class like:
//as a class attribute
Int[]checkboxesIds = new array[] {ids in xml};
//in the loop
CheckBox ch = findViewById(ids[i])
ch.ischecked();
but its wrong for large of data.

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 :)

How to get the checked item id in custom list view with multiple selections in android

How to get the checked item id (custom id, not the position or name of the selected item -in my case order id i need to retrieve) in a custom list view with multiple selections in android.
I have Order name and Order id from json and its populated in custom list view ,In the custom list view i have text view and check box but how to get the Orderid's of the selected/checked Orders.
I have a button when i click the button i need to retrieve the id not the name or position , in my case i need order id to be retrieved
You just need to call ListView.getCheckedItemIds(). It will return a long[] with all checked ids.
There is also ListView.getCheckedItemPositions() which will give you all checked positions.
Make sure you set ListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE) in onCreate() or whereever you set up your views (or in layout xml).
To get the checked values you just need to do this:
SparseBooleanArray checked = mListView.getCheckedItemPositions();
for (int i = 0; i < checked.size(); i++) {
if (checked.valueAt(i)) {
int pos = checked.keyAt(i);
Object o = mListView.getAdapter().getItem(pos);
// do something with your item. print it, cast it, add it to a list, whatever..
}
Jerry, set your order object as tag to the view which has selection event [CheckBox, TextView, Row view], when user select item you can get selected order object from tag and you can get any member of that object(order). for ex.
Order Object
Order {
int id;
String name;
boolean isSelected;
//add getters and setters
}
void getview(...) {
View v = //inflate view
CheckBox cb = (CheckBox) v.findViewById(..);
cb.setTag(yourlist.get(position));
cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
((Order) buttonView.getTag()).setSelected(isChecked);
}
});
}
I Solved and got the OrderId by using below code , this worked for me and i could retrieve the custom ORDERID which i passed to the list
int isSelectedOrderNumber=0;
mOpenOrdersSelected = new ArrayList<OpenOrders>();
StringBuffer sb = new StringBuffer();
Iterator<OpenOrders> it = mOpenOrders.iterator();
while(it.hasNext())
{
OpenOrders objOpenOrders = it.next();
//Do something with objOpenOrders
if (objOpenOrders.isSelected()) {
isSelectedOrderNumber++;
mOpenOrdersSelected.add(new OpenOrders(objOpenOrders.getOrderID(),objOpenOrders.getOrderName()));
sb.append(objOpenOrders.getOrderID());
sb.append(",");
}
}
//Below Condition Will Check the selected Items With parameter passed "mMAX_ORDERS_TOBEPICKED"
if(isSelectedOrderNumber<1){
ShowErrorDialog("Please Select atleast One order");
return;
}
if(isSelectedOrderNumber>mMAX_ORDERS_TOBEPICKED){
ShowErrorDialog(" Select Maximum of "+mMAX_ORDERS_TOBEPICKED+ " Orders only to process");
return;
}
Log.d(MainActivity.class.getSimpleName(), "cheked Order Items: " +sb);
Toast.makeText(getApplicationContext(), "cheked Order Items id:" +sb, Toast.LENGTH_LONG).show();

Android Development - isChecked Checkbox using simple_list_item_multiple_choice and CHOICE_MODE_MULTIPLE

I am using simple_list_item_multiple_choice with list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); to create a list of check boxes populated from a database query. I am then using onListItemClick to handle the clicking of the list, again that is working fine. What I can find no way of doing (after 5 days) is writing an if statement based on whether or not the check box attached to the list item is checked. What I need is the equivalent of the example below which works perfectly for a check box where I can use the android:onClick element to fire the method below.
public void onCheckboxClicked(View v) {
// Perform action on clicks, depending on whether it's now checked
if (((CheckBox) v).isChecked()) {
Toast.makeText(this, "Selected", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Not selected", Toast.LENGTH_SHORT).show();
}
}
This is critical to my app so any advice would be greatly appreciated. Below is the simpleCusrorAdapter is am using:
Cursor cursor3 = db.rawQuery("SELECT _id, symname FROM tblsymptoms WHERE _id IN ("+sympresult+") ", null);
adapter = new SimpleCursorAdapter(
this,
android.R.layout.simple_list_item_multiple_choice,
cursor3,
new String[] {"symname","_id"},
new int[] {android.R.id.text1});
setListAdapter(adapter);
ListView list=getListView();
list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
I have solved the problem after finding this very useful blog item
I changed my onListItemClick to the following and it works like a dream:
public void onListItemClick(ListView parent, View view, int position, long id) {
CheckedTextView check = (CheckedTextView)view;
check.setChecked(!check.isChecked());
boolean click = !check.isChecked();
check.setChecked(click);
if (click) {
Toast.makeText(this, "Not Selected", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Selected", Toast.LENGTH_SHORT).show();
}
}
If I understand correctly, each row in your list has a checkbox. When an item in the list is selected you want to be able to tell if the corresponding checkbox is checked?
Try to use the setTag(...) method on each list item View object. Then when onListItemClick() method is called you can call getTag(...) on the view (which will return your checkbox). I assume that you are using a custom Adapter to populate the list. While populating you want to call:
setTag( CHECKBOX_KEY, checkbox );
For example:
protected void onListItemClick(ListView l, View v, int position, long id) {
CheckBox cb = (CheckBox)v.getTag( CHECKBOX_KEY );
boolean isChecked = false;
if( null != cb ) {
isChecked = cb.isChecked();
}
// .. do whatever you have to here...
}
Hope this helps...

AlertDialog.Builder problem with accessing a specific row

I've been working on this application but have come across a problem that I have been unable to figure out. I have a listview that is populated with the contents from an adapter, and each row has their specific information (Uniform). The problem comes when I try to retrieve the value of a checkbox that is found in that particular row.
The code in question is below:
I build an AlertDialog object so I can get my information from the user. My layout code consists of a LinearLayout in horizontal orientation with 3 elements an image, text, check box. I build my AlertDialog with R.layout.listview_layout, which is a custom layout that I made.
One thing I tried to do is get the CheckBox View from the adapter, however; when I look at it via cb.isChecked(), no matter what row i'm on its always unchecked (aka false). In order to debug this further I took the same adapter and retrieved the text via the same methodology and it returned specific information about that row, as it should.
Any ideas how I can handle this?
Simply Put:
I would just like to get the value of the CheckBox at each given row
c = help.returnContacts();
AlertDialog.Builder ab = new AlertDialog.Builder(this);
ab.setTitle("Select contacts");
final SimpleCursorAdapter adapter = new SimpleCursorAdapter(
getApplicationContext(), R.layout.listview_layout, c,
new String[] { ClientOpenDbHelperUtility.COL_NAME,
ClientOpenDbHelperUtility.COL_SEL }, new int[] {
R.id.txt_name, R.id.cb_select });
ab.setAdapter(adapter, null);
ab.setPositiveButton("Confirm", new Dialog.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Cursor c = adapter.getCursor();
for (int i = 0; i < adapter.getCount(); i++) {
CheckBox cb = (CheckBox) adapter.getView(i, null, null)
.findViewById(R.id.cb_select);
TextView t = (TextView) adapter.getView(i, null, null)
.findViewById(R.id.txt_name);
Log.d("DEBUG", "Checked = " + cb.isChecked());
Log.d("DEBUG", "Message = " + t.getText().toString());
if (cb.isChecked()) {
help
.updateSelection(
c
.getColumnIndex(ClientOpenDbHelperUtility.COL_UID),
true);
} else {
help
.updateSelection(
c
.getColumnIndex(ClientOpenDbHelperUtility.COL_UID),
false);
}
}
c.close();
help.closeAll();
}
});
ab.show();
}
Thanks for reading!
You shouldn't call getView directly. Doing so generates a fresh view (or recycles and overwrites an old one) based on the contents of your database.
Also, once your rows scroll off the top or bottom of the screen they will be recycled for use in new rows that appear. All of your data but the currently visible rows are most likely to have already vanished by the time your onClick method gets called.
You have two options:
Persist changes immediately to the database - set an OnClickListener on your checkbox or on the row and update your database on each click event.
Save changes to an instance variable and then apply later - define a Map<Integer, Boolean> changes instance variable for your activity and call changes.put(position, isChecked) whenever there is a click. Then when your user clicks "Apply" or whatever your onClick is, go through changes and persist each one to the database. It's basically the same as what you have now except you would be using a stable object to store the unsaved changes.

Categories

Resources