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.
Related
if (RFidList.size() >0){
for (String s: RFidList){
RFidTagValueList.remove(s);
}
}
mTimeAdapter.notifyDataSetChanged();
dialog.dismiss();
when choose multiple items in recyclerview checkbox not working / and am use private ArrayList<String> data = new ArrayList<>();
You can't move and delete from the list. The best option to do this is to have an array that will remember the state of the checkbox. Scrolling through your recycler view will always change the state of the checkbox and maybe won't remember it. The way to do this is to add an array of boolean
private boolean[] checkStates;
then inside your constructor of the adapter do this.
checkStates = new boolean[data.size()];
This way you'll create an array of boolean filled with FALSE value the same size your data array is. Now, inside your adapter when you are binding your view do this for the checkbox.
holder.checkbox.setChecked(checkStates[position]);
Also, don't use onCheckedChangeListener on checkbox inside adapter. This will be called even when you scroll and it will change whatever you are doing inside the function. What you can do is override onClick for the checkbox, but there is something tricky here. When you click the checkbox to check it, inside the onClick method the view will have the state as it is already checked so to follow this do it like this:
holder.checkbox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Checkbox c = (CheckBox) v;
checkStates[position] = c.isChecked();
}
});
I wrote this from my head and maybe there are some mistakes but you'll get the point. The animation of the check state will be handled you just need to handle changes inside the checkStates array.
Now your checkbox will always have the state it had before. After this, you can create a function to delete items from your data.
public void removeItems() {
ArrayList<YOUR-MODEL> items_to_delete = new ArrayList<>();
for (int i = 0; i < checkStates.length(); ++i) {
if (checkStates[i]) items_to_delete.add(data.get(i]);
}
data.removeAll(items_to_delete);
notifyDataSetChanged();
checkStates = new boolean[data.size()];
}
This works if your data is a type of ArrayList. I think this is the best way to go.
I am creating a RecyclerView which has items. Each item has a CheckBox, ImageButton and a TextView as stated below:
public class RecyclerViewViewHolder extends RecyclerView.ViewHolder {
RelativeLayout item;
TextView id;
TextView name;
ImageButton delete;
CheckBox checkBox;
public RecyclerViewViewHolder(View view) {
super(view);
item = (RelativeLayout) view.findViewById(R.id.layout_item_item);
id = (TextView) view.findViewById(R.id.layout_item_id);
name = (TextView) view.findViewById(R.id.layout_item_name);
delete = (ImageButton) view.findViewById(R.id.layout_item_delete);
checkBox = (CheckBox) view.findViewById(R.id.layout_item_checkbox);
}
}
I want the checkbox view to be checked only if a certain value in a column of a database is equal to 1. If the value is 0, it should not be checked. I have started off with the code below:
SQLiteDatabaseAdapter database = new SQLiteDatabaseAdapter(context);
database.open();
Cursor cursor = database.getAllItems(table);
if (cursor.moveToFirst()) {
do {
if (cursor.getInt(2) == 0) {
viewHolder.checkBox.setChecked(false);
}
else {
viewHolder.checkBox.setChecked(true);
}
} while (cursor.moveToNext());
}
database.close();
This code works but it checks the first row in the database and if the checked column is 1, it changes every single CheckBox to be checked. I only want the CheckBox associated with one particular row to be checked, not every single one. How do I exactly do that?
The problem is that you are iterating through every row in the cursor. Instead, you need to go to the row for the current position by calling cursor.moveToPosition().
In pseudocode, the steps you should follow are
Open the database.
Get the cursor.
Move the cursor to the correct row.
Retrieve the value from the cursor.
Set the Checkbox to the correct state.
Close the cursor.
I leave the details as an exercise for the reader.
I recommend that you create a HashMap<> and link the IDs and the checked states. Then, you can reference from the HashMap<> and get the checked states.
HashMap<Integer, Integer> hashMap = new HashMap<Integer, Integer>();
Then, in your onBindViewHolder function, you can use the following to check you CheckBox:
if (hashMap.get(position) == 0) {
// not checked
}
else {
// checked
}
Make sure you add the IDs and checked states from your SQLite database.
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 (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();
is it possible to programatically access specific rows in a list of CheckedTextViews to change the state of their textboxes?
my program has a listview which has several CheckedTextViews which the user can press to toggle state.
I want to save the state of the checkboxes when the user leaves the activity, so I have in my onPause method:
public void onPause(){
super.onPause();
SparseBooleanArray positions;
positions = listView.getCheckedItemPositions();
ListAdapter items = listView.getAdapter();
int j = items.getCount();
ArrayList<Long> ids = new ArrayList<Long>();
for (int k =0; k < j;k++){
if(positions.get(k)==true){
ids.add(items.getItemId(k));
}
}
this.application.getServicesHelper().open();
this.application.getServicesHelper().storeServices(ids,visit_id);
this.application.getServicesHelper().close();
}
which very simply iterates the list view, adds the checked items to an ArrayList and then saves that list of ids to the database.
My problem lise in trying to reset the list once a user goes back to that activity.
so far in my onStart method, I recall the checked items from the database, but I do not know how to march the ids returned to the listview elements. can I do something like:
listView.getElementById(id_from_database).setChecked?
I know I cant use getElementById but I have it here to show what I mean
Thanks in advance
Kevin
You can call
listView.setItemChecked(int position, boolean value)
This is what Ive ended up doing.. but it seems like a complete hack.
Basically I have to set up a double for loop.. one to iterate through my list elements, and one to iterate through the cursor that I have retreived my check list state (a simply array of ids of elements that were checked when state was last saved)
my outer for iterates through the list elements checking each id against a loop through the list of ids to be set as checked. if they equal each other then set that item as checked.
// mAdapter is contains the list of elements I want to display in my list.
ServiceList.this.setListAdapter(mAdapter);
// Getting a list of element Ids that had been previously checked by the user. getState is a function I have defined in my ServicesAdapter file.
Cursor state = ServiceList.this.application.getServicesHelper().getState(visit_id);
int checks = state.getCount();
int check_service;
int c = mAdapter.getCount();
if(checks>0){
state.moveToFirst();
for (int i=0; i<checks; i++) {
// set check_service = the next id to be checked
check_service = state.getInt(0);
for(int p=0;p<c;p++){
if(mAdapter.getItemId(p)==check_service){
// we have found an id that needs to be checked. 'p' corresponds to its position in my listView
listView.setItemChecked(p,true);
break;
}
}
state.moveToNext();
}
}
ServiceList.this.application.getServicesHelper().close();
Please tell me there is a more efficient way of achieving this!!
Thanks
Kevin