-2

I want to delete an element from the list when a button x is clicked on the layout of a list element. Here is my java code, onNext() is working for adding an element to the list . but the onDelete isnt working.The textView4 element has numbers starting from 1 to n when new elements are added

 public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list2);
        arrayList = new ArrayList<String>();
        arrayList.add("1");
        adapter2 = new ArrayAdapter<String>(this, R.layout.list2_layout, R.id.textView4, arrayList);

        ListView myList2 = (ListView)
                findViewById(R.id.listView2);
        myList2.setAdapter(adapter2);


    }

    public void onNextItem(View v)
    {

            counter++;
            String str=Integer.toString(counter);
            arrayList.add(str);
        adapter2.notifyDataSetChanged();

    }
    public void onDeleteItem(View v2)
    {

        arrayList.remove(R.id.textView4);
        adapter2.notifyDataSetChanged();

    }
  • possible duplicate of [Remove ListView items in Android](http://stackoverflow.com/questions/2558591/remove-listview-items-in-android) – 2Dee Jun 10 '15 at 09:19
  • if you just want to delete the last added item use: `arrayList.remove(arrayList.size()-1);` – Strider Jun 10 '15 at 09:21

4 Answers4

1

you should not be passing the R.id.textView4 to remove the 4th textView

 arrayList.remove(R.id.textView4);

You will need to do something like arrayList.remove(4); to delete the forth element from the list

Dominic D'Souza
  • 961
  • 2
  • 7
  • 16
1

on onNextItem(View v):

you are adding an integer(counter) converted to string to the list(arrayList.add(str);)

but on onDeleteItem(View v2):

you are trying to remove a view from the list (arrayList.remove(R.id.textView4);)

hrskrs
  • 4,447
  • 5
  • 38
  • 52
0

Your trying to remove Textview

arrayList.remove(R.id.textView4); 

do it like this

arrayList.remove(clickeditempostion);
adapter2.notifyDataSetChanged();
Anil Meenugu
  • 1,411
  • 1
  • 11
  • 16
0

You can do something like this.

arrayList.remove(CURRENT_INDEX_OF_ARRAYLIST);
        adapter2.notifyDataSetChanged();
Shoeb Siddique
  • 2,805
  • 1
  • 22
  • 42