'android - removing item from ListView on long click

I'm having some troubles while trying to remove an item from the list view on long click. Below is the code:

public class MListViewActivity extends ListActivity {

private ListView lv;
private String[] some_data = null;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    some_data = getResources().getStringArray(R.array.mdata);

    // Bind resources Array to ListAdapter
    ArrayAdapter<String> myAdapter = new ArrayAdapter<String>(this,
            R.layout.list_item, R.id.label, some_data);
    this.setListAdapter(myAdapter);

    lv = getListView();
    lv.setDividerHeight(3);

    lv.setOnItemLongClickListener(new OnItemLongClickListener() {

        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view,
                int arg2, long arg3) {

            // Can't manage to remove an item here

            return false;
        }
    });
}

Any help is appreciated



Solution 1:[1]

try

lv.setOnItemLongClickListener(new OnItemLongClickListener() {

    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view,
            int position, long arg3) {

              myAdapter.remove(some_data[position]);
              myAdapter.notifyDataSetChanged();

        return false;
    }

});

Solution 2:[2]

I had issues using this method. and i solved it using this.

            listStat.remove(listStat.get(arg2));
            lvStat.requestLayout();
            adapterStat.notifyDataSetChanged();

I think this will help to others.

Solution 3:[3]

itemAdapter = new ArrayAdapter<String>(
        view.getContext(),
        androidx.appcompat.R.layout.support_simple_spinner_dropdown_item,
        itemViewModel.getItems().getValue().stream().map(TaskCard::getTitle).collect(Collectors.toList())
);
ListView listview = view.findViewById(R.id.item_listview);
listview.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int i, long l) {
        itemAdapter.remove(itemAdapter.getItem(i));
        return true;
    }
});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Georgy Gobozov
Solution 2 Borshon saydur rahman
Solution 3 Himself65