Hi I have a listview showing an arraylist, when an item is clicked it is added to another arraylist and displayed in another activity. What is my problem? I want that if an item (eg a dog) I touch once, is added to the second activity, and it shows. But if I were to touch the item (dog) is not added again.
We would say that I want to check if it exists, not add.
I've tried so, but without success.
if (page2 == null)
{
page2 = (ListView) LayoutInflater.from(Local_mostrar_bebidaActivity.this).inflate(R.layout.page_two_viewpager_listview, null);
page2.setAdapter(adapterlistvMenuVINOSespumosos);
page2.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
if (MiPedidoActivity.itemsListVMiPedido.contains( position)){}
else
MiPedidoActivity.itemsListVMiPedido.add(itemsListVMenuVINOSespumosos.get(position));
}});
}
page = page2;
break;
Any ideas?
You have:
if (MiPedidoActivity.itemsListVMiPedido.contains( position)){}
else
MiPedidoActivity.itemsListVMiPedido.add(itemsListVMenuVINOSespumosos.get(position));
You are checking if itemsListVMiPedido
contains the integer, position
, but you are adding itemsListVMenuVINOSespumosos.get(position)
to the list. You need to check if the list contains them item, not the index (think of it exactly like what you are trying to do: "do not add item to list if list already contains item). You probably mean something like this (I just made up Item
for example, use whatever class your objects are):
Item item = itemsListVMenuVINOSespumosos.get(position);
if (MiPedidoActivity.itemsListVMiPedido.contains(item)) { // <- look for item!
// ... item already in list
} else {
MiPedidoActivity.itemsListVMiPedido.add(item);
}
By the way, as a suggestion, if your item classes have equals()
and hashCode()
properly implemented, consider a LinkedHashSet
(which will preserve insertion order but will not allow duplicates). There are other Set
implementations that may be useful too (e.g. TreeSet
if your items implement Comparable
), depending on your ordering/sorting requirements.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With