I have developed a code in which i have populated list view dynamically.
now i want to delete the selected item from list view on button click(on pressing delete button)
I have searched out this in this site but didn't got any exact solution so i am posting this question
please help me how to do this :
code on delete buttons onClickListener is as shown below :
DeleteButton.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
if (idx >= 0) {
Log.v("Item index deleted", idx + "");
idx = OdrLst.getCheckedItemPosition();
String delete = (String) ((OdrLst.getAdapter())
.getItem(idx));
// Long deteteId = OdrLst.getAdapter().getItemId(idx);
Log.d("Item deleted", delete);
Log.d("adapter count before", adapter.getCount() + "");
Log.d("lv count before", OdrLst.getCount() + "");
// Log.d("listitems count before", listItems.+"");
adapter.remove(delete);
//listItems.remove(idx);
adapter.notifyDataSetChanged();
OdrLst.setAdapter(adapter);
// OdrLst.removeViewAt(idx);
// adapter.clear();
Log.d("adapter count after", adapter.getCount() + "");
Log.d("lv count after", OdrLst.getCount() + "");
//adapter.notifyDataSetChanged();
// Log.v("adapter count after 1", adapter.getCount()+"");
}
// cleared = false; // <--- nope, we did not clear the value yet
// delItem();
}
});
This code shows exact position and item to be deleted but the item not gets removed from the listview...
Try adding this after removing the item.
adapter.notifyDataSetChanged();
You can make a customized Listview containing check boxes or imageview and then use Arraylist to get the items which were clicked in the list.
refer these link:
Remove item from the listview in Android
Related
how can I limit the number of checked checkboxes in android? I have multiple checkboxes being added programatically and it's difficult to keep track of them.
here's the code used to add them:
final CheckBox currentVariantCheckbox = new CheckBox(getApplicationContext());
checkBoxGroupList.add(currentVariantCheckbox);
Log.d(TAG, "onDataChange: added " + currentVariantCheckbox + " to the checkboxgrouplist; size = " + checkBoxGroupList.size());
currentVariantCheckbox.setChecked((Boolean) currentVariant.child("checked").getValue());
LinearLayout checkboxGroupLayout = new LinearLayout(getApplicationContext());
checkboxGroupLayout.setOrientation(LinearLayout.HORIZONTAL);
currentVariantCheckbox.setText(currentVariant.child("name").getValue(String.class));
TextView currentVariantPriceTag = new TextView(getApplicationContext());
checkboxGroupLayout.addView(currentVariantCheckbox);
if (currentVariant.child("price").exists()) {
currentVariantPriceTag.setText("+" + currentVariant.child("price").getValue(float.class).toString() + " €");
checkboxGroupLayout.addView(currentVariantPriceTag);
ok so instead of using a onCheckedStateChangedLister I used OnClickListener. And I created an ArrayList to keep track of all the checked checkboxes:
final ArrayList<CheckBox> checkedList = new ArrayList<>();//this is the list to keep track of checked checkboxes
int maxOptions = 3
int minOptions = 1
currentVariantCheckbox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Boolean currentCheckState = currentVariantCheckbox.isChecked();
if (currentCheckState) {//if the clicked checkboxes was unchecked and is now checked
checkedList.add(currentVariantCheckbox);
Log.d(TAG, "onClick: added " + currentVariantCheckbox + " ;checkedList.size is now: " + checkedList.size());
if (checkedList.size() >= maxOptions) {
checkedList.get(0).setChecked(false);
checkedList.remove(0);// if limit exceeded remove the first element from the checked list
Log.d(TAG, "onCheckedChanged: checkedList's size is now: " + checkedList.size());
}
} else if (checkedList.size() <= minOptions) {
currentVariantCheckbox.setChecked(true);
// if the list is empty just add the clicked checkbox to the list for example here 0
// and it will be checked automatically
} else {
checkedList.remove(currentVariantCheckbox);
// if the checkbox was already checked and no limit is exceeded
// then it will be unchecked therfore it should be removed from checkedList
}
}
});
Actually i'm developing an inventory app where i scan some EAN codes then i insert the quantity of an item and then i add it to an ArrayList in recyclerView.
For now i had no problem as i've made the inventory part where the items had to have different lines for each in recyclerView but now i have to make the order part and here if an item exist yet in ArrayList i have to sum it's quantity and put it to top of recyclerView.
I was trying to make something like a for loop when i'm going to add a new item and check if it's exist in ArrayList, if it's exist i was going to sum that item quantity with old one but the problem was that sometimes the app was going to crash and that the item wasn't going on top of recyclerView.
Do you have any suggestion on how can i do it?
for (ItemModel item : itemModel) {
if (item.getCodiceArticolo()
.equals(code.getText()
.toString())) {
item.setQta(String.valueOf(
Integer.parseInt(item.getQta()) + 1));
}
}
I was trying to make something like that.
Try this code:
ItemModel matchedItem = null;
int matchedItemIndex = -1;
for (ItemModel item : itemModel) {
if (item.getCodiceArticolo()
.equals(code.getText()
.toString())) {
item.setQta(String.valueOf(
Integer.parseInt(item.getQta()) + 1));
matchedItem = item;
matchedItemIndex = itemModel.indexOf(item);
break;
}
}
if (matchedItemIndex > -1) {
itemModel.remove(matchedItem);
itemModel.add(
0,
matchedItem);
notifyItemMoved(index,
0);
}
You do not adderror log to your list, so I guess your program crashes because sometimes there is a value that has no quantity (there is no valid number) and therefore can not parse the number, so in this case you just write that there is one item in list that has not been there yet.
for (ItemModel item : itemModel) {
if (item.getCodiceArticolo()
.equals(code.getText()
.toString())) {
try {
item.setQta(String.valueOf(
Integer.parseInt(item.getQta()) + 1));
}
catch (Exception ex) {
item.setQta(String.valueOf(1));
}
}
}
If this does not help, please attach error log.
Since the app is crashing, your ArrayList might not have been initialized as suggested in the comments.
For checking if the item exists you can use
if (arraylist_of_items != null && arraylist_of_items.contains(item)) {
// do your stuff here
}
Three days a go i was getting the "ConcurrentModificationException" but now i'm trying another approach inspired by other answers or better the following one:
boolean nuovo = true;
for (ItemModel itemModels : itemModel) {
if (itemModels.getCodiceArticolo()
.equals(code.getText()
.toString())) {
itemModels.setQta(String.valueOf(
Integer.parseInt(itemModels.getQta()) + 1));
nuovo = false;
break;
}
}
if (nuovo) {
itemModel.add(new ItemModel(
code.getText()
.toString(),
"1"));
}
And is not crashing anymore and seems to work fine.
Thank's all for suggestions.
UPDATE
THANKS TO kartik malik ANSWER i was able to even "update" my items by adding the last one added on top, as i'm using reverse recyclerView i've done it by this wasy instead of putting the item to position 0
ItemModel matchedItem = null;
int matchedItemIndex = -1;
boolean nuovo = true;
for (ItemModel itemModels : itemModel) {
if (itemModels.getCodiceArticolo()
.equals(code.getText()
.toString())) {
itemModels.setQta(String.valueOf(
Integer.parseInt(itemModels.getQta()) +
Integer.parseInt(qta.getText()
.toString())));
MediaPlayer mpFound = MediaPlayer.create(
OrdiniActivity.this,
R.raw.errorsound);
mpFound.start();
matchedItem = itemModels;
matchedItemIndex = itemModel.indexOf(itemModels);
nuovo = false;
break;
}
}
if (matchedItemIndex > -1) {
itemModel.remove(matchedItem);
itemModel.add(matchedItem);
}
if (nuovo) {
itemModel.add(new ItemModel(
code.getText()
.toString(),
qta.getText()
.toString()));
}
With the boolean i'm checking if the item exist or not and if it doesn't exist i add the item as a new one.
I have a multiSelec listView fills with days. I´m getting the items selected, my problem is when I click in one list field in order to unselect it. An example:
I check the position 1,2,3,4,5 on the list and after that I uncheck the 4,5 position , so finally I have 3 fields checked.
With my code I get 5 values checked instead 3 .
¿Can anyone help me?
What I'm doing wrong?
private void gettingDaysChecked(){
boolean isSomethingChecked = false;
SparseBooleanArray checked = mListView.getCheckedItemPositions();
Log.d(Constants.TAG,"cheched size is "+checked.size() );
if (checked.size()>0)
isSomethingChecked=true;
if (isSomethingChecked) {
for (int i = 0; i < checked.size(); i++) {
int positionItem = checked.keyAt(i);
Log.d(Constants.TAG, "in position" + positionItem);
localList.add(positionItem);
}
app.setDaysCheckedFilterPeriod(localList);
}else if(!isSomethingChecked){
Log.d(Constants.TAG,"nothing checked ");
}
}
I have a listView and I want to print the arrrayList which contains the selected items.
I can show the choice that I choose every time. i.e. if I select a choice, I can print it in a toast (I mark it in my code as a comment), but I want to print the whole choices together.
Any help please?
Thanks..
If I understand correctly, you want to display the contents of your arrayList in a Toast.
Like donfuxx said, you need to create your arrayList outside of your onclicklistener.
As the user clicks an item, it will be added to your arrayList.
Then loop over the list to fill a string called allItems, then show allItems in a toast.
ArrayList<String> checked = new ArrayList<String>();
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String listItem = (String) listView.getItemAtPosition(position);
if(!checked.contains(listItem)){ //optional: avoids duplicate Strings in your list
checked.add((position+1), listItem);
}
String allItems = ""; //used to display in the toast
for(String str : checked){
allItems = allItems + "\n" + str; //adds a new line between items
}
Toast.makeText(getApplicationContext(),allItems, Toast.LENGTH_LONG).show();
}
});
Well you have the right concept, jsut wrong execution here is the part you missed out on:`
ArrayList<String> checked = new ArrayList<String>();
checked.add((position+1), listItem);
Toast.makeText(getApplicationContext(),checked.get((position+1)), Toast.LENGTH_LONG).show();`
You have to get the position of the element in the ArrayList which you require to fetch, hence
checked.get(array position of element here)
If you want to show every item that is in the ArrayList you can use a simple loop and add them to a string like this:
...
checked.add((position+1), listItem);
String tempString = "";
for(int x = 0; x < checked.length(); x++) {
tempString = tempString + ", " + checked.get(x);
}
tempString = tempString.substring(2);
Toast.makeText(getApplicationContext(),tempString, Toast.LENGTH_LONG).show();
EDIT modified it a bit to only put commas between items
How do I replace a value from an array list dynamically when the user edits the array of values? I used arr_list.set(count,"replace value") inside button click.Action done by using the button click event. So I used count for index of arr_list. I have an issue as I click the button it replaces all the values in arr_list. I want to replace particular edit values done by user.
if (v == right) {
if (riskList.size() == 0) {
} else
{
try {
riskList.set(count2,key.getText().toString());
Log.i("dfDF", "" + count2);
key.setText(riskList.get(count2).toString());
toGetIndex = key.toString();
int indexPlus = riskList.indexOf(toGetIndex);
risk.setText(descList.get(count2).toString());
totalRiskin.setText(count2 + 1 + "/" + totalRisks);
} catch (IndexOutOfBoundsException ex) {
Toast.makeText(SalesEditActivity.this,
"There is no next element", Toast.LENGTH_SHORT)
.show();
}
count2 = count2 + 1;
}
}
I have used previous and next button to display array list values according to index.ie count. I also want edit array list values,it will be replace the current index value.
Try declaring your array list as static.