Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add item to arraylist if it does not already exist in list

Tags:

java

android

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?

like image 948
Emmanuel Guther Avatar asked Mar 02 '14 20:03

Emmanuel Guther


1 Answers

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.

like image 91
Jason C Avatar answered Nov 11 '22 07:11

Jason C