0

I Have problem, I want to delete a row frow listView and this element from ArrayList.

This is my new ArrayAdapter

private ExpenditureAdapter adapter = null;

and I adding to it data using:

adapter = new ExpenditureAdapter(this,R.layout.activity_show_list,addExpenditure.getExpidentures());
        setListAdapter(adapter);

It works correctly, but I want create OnItemClickListener and use it to delete data from listView and from ArrayList<Expenditure>, but how to do it ?

My effort:

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                addExpenditure.getExpidentures().remove();
            }
        });

But ofc it doesn't work.How get index to delete this ?

3
  • 1
    show your effort please... Commented Jun 8, 2016 at 13:59
  • 1
    Remove the item from your arraylist then notify the arrayadapter(notifydatasetchanged) Commented Jun 8, 2016 at 14:00
  • position is the index of the selected item Commented Jun 8, 2016 at 14:08

2 Answers 2

2

Try this

 YourListView.setOnItemClickListener(new OnItemClickListener()
   {
      @Override
      public void onItemClick(AdapterView<?> adapter, View v, int position,
            long arg3) 
      {
              YourArrayList.remove(position);
            YourArrayAdapter.notifyDataSetChanged();
      }
   });
Sign up to request clarification or add additional context in comments.

4 Comments

But how create Listener on Click ?
you have to create onitemclicklistener not onclicklistener for the listview
Almost, now I have problem with listView = (ListView)findViewById(); i have this error Your content must have a ListView whose id attribute is 'android.R.id.list'
If you are using ListActivity your xml file must specify the keyword android while mentioning to a ID <ListView android:id="@android:id/list" android:layout_width="fill_parent" android:layout_height="fill_parent"/>
0

You almost have it working, change your listener to this:

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
     @Override
     public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
         addExpenditure.getExpidentures().remove(position);
         parent.notifyDataSetChanged();
     }
});

Basically, if you are changing the underlying data of an adapter (your ArrayList), you need to notify the adapter so it can update the list accordingly. This will remove the item and then redraw the list.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.