0

I have 2 Array list -> ListView, if you click on item in ListView it adds this item to the second ListView. If the clicked item is already in the second list, instead of adding it again it replaces text with number followed by item name.

But the counter is global for all items, so if i add another item it still adds the same number for it. I need something that will generate variable name from clicked item name and then adds counter to right item. Here's the code, thanks in advance.

menuNapoje.setOnItemClickListener(new OnItemClickListener(){
        int pocet= 2;
        String x = "x ";

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                        int position, long id) {

            if(rekapitulaceObjArray.contains(menuNapojeArray.get(position)) || rekapitulaceObjArray.contains(pocet-1 + x + menuNapojeArray.get(position))) {

                rekapitulaceObjArray.set(position, pocet + x + menuNapojeArray.get(position));                          
                pocet++;

            } else {

                rekapitulaceObjArray.add(menuNapojeArray.get(position));
            }

            rekapitulaceAdapter.notifyDataSetChanged();
            Toast.makeText(getApplicationContext(), "Položka " + menuNapojeArray.get(position) + " byla pridána", Toast.LENGTH_SHORT).show();


       }
 });
venergiac
  • 7,469
  • 2
  • 48
  • 70
user3185930
  • 29
  • 1
  • 1
  • 11

2 Answers2

0

Rather than trying to generate a variable name to store something (which is rather complicated and probably not what you really want to do), why not generate a key that you can put into a HashMap or something similar?

This way it's just a string key that you can generate/manipulate easily, and getting the value is just a map lookup instead of a variable reference.

Krease
  • 15,805
  • 8
  • 54
  • 86
0

What type does menuNapojeArray.get(position) return? You have to make sure that this type implements the equals() method properly. Otherwise these two objects cannot be compared if they don't share the same instance. Hence another copy is added again.

See also

What issues should be considered when overriding equals and hashCode in Java?

How to implement hashCode and equals method

Community
  • 1
  • 1
Lars Blumberg
  • 19,326
  • 11
  • 90
  • 127