Search code examples
androidandroid-listviewandroid-alertdialogonlongclicklistener

How to delete an item in the listview using onItemLongClick?


I already created an onItemLongClick that will display the following alertdialog when listview is long clicked. The problem with my code is that even if I selected "Edit" as an option from the list, the item will still be deleted.

I wanted to put an intent when I click "Edit" and delete the item when I click "Delete" and I have no clue on how to create a conditional statement to do that.

enter image description here

Here is my code:

MainActivity.java

<-- start of snippet -->

@Override
public boolean onItemLongClick(AdapterView<?> View view, final int position, long id){
   Persons selectedPersons = this.list.get(position);
   String name = selectedPersons.getName();

   final CharSequence[] options = {"Edit", "Delete"};

   builder.Items(options, new DialogInterference.OnClickListener(){

      @Override
      public void onClick(DialogInterface dialog, int which){
          list.remove(position);
          adapter.notifyDataSetChanged();
          Toast.makeText(MainActivity.this, "Item deleted!", Toast.LENGTH_LONG).show();

}
});
AlertDialog dialog = builder.create();
dialog.show();

return true;

}

<-- end of snippet -->

Solution

  • Put an if condition inside your onClick like this -

    @Override
     public boolean onItemLongClick(AdapterView<?> View view, f final int position, long id){
        Persons selectedPersons = this.list.get(position);
        String name = selectedPersons.getName();
    
        final CharSequence[] options = {"Edit", "Delete"};
    
       builder.Items(options, new DialogInterference.OnClickListener(){
    
          @Override
          public void onClick(DialogInterface dialog, int which){
              if(options[which].equals("Delete") {
                  list.remove(position);
                  adapter.notifyDataSetChanged();
                  Toast.makeText(MainActivity.this, "Item deleted!", Toast.LENGTH_LONG).show();
               } else if(options[which].equals("Edit") {
                     //Do edit
               }
    
          }
    });