Deleting Selected Items from ListView in Android

June 21, 2012
By

In this article, we will create an application in which users select the required items to be deleted and click on “Delete Selected Items” button for deleting them. Actually this article is an extension of the article Dynamically add items to ListView in Android, in which we have created an application to add user input text to listview. In this article, user can add as well as delete items from the listview.


1. Create an Android project namely “ListViewDeleteItems”

New Android Project

Figure 1: New Android Project


2. Select Build Target for this application

Select build target

Figure 2: Select build target


3. Enter application details

Application Details

Figure 3: Application Details


4. Open and update the file res/values/strings.xml with the given below code

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">Hello World, MainActivity!</string>
    <string name="app_name">ListViewDeleteItems</string>
    <string name="hintTxtItem">Enter an item here ...</string>
    <string name="lblBtnAdd">Add Item</string>
    <string name="txtEmpty">List is empty</string>
    <string name="lblBtnDel">Delete Selected Items</string>
</resources>

5. Open and update the file res/layout/main.xml with the given below code

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <EditText
        android:id="@+id/txtItem"
        android:layout_width="240dp"
        android:layout_height="wrap_content"
        android:inputType="text"
        android:hint="@string/hintTxtItem"
    />

    <Button
        android:id="@+id/btnAdd"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/lblBtnAdd"
        android:layout_toRightOf="@id/txtItem"
    />

    <TextView
        android:id="@android:id/empty"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/txtItem"
        android:text="@string/txtEmpty"
        android:gravity="center_horizontal"
    />

    <ListView
        android:id="@android:id/list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/txtItem"
        android:choiceMode="multipleChoice" >
    </ListView>

    <Button
        android:id="@+id/btnDel"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:text="@string/lblBtnDel" />
</RelativeLayout>

6. Open and update the file /src/in/wptrafficanalyzer/listviewdeleteitems/MainActivity.java with the given below code


package in.wptrafficanalyzer.listviewdeleteitems;

import java.util.ArrayList;

import android.app.ListActivity;
import android.os.Bundle;
import android.util.SparseBooleanArray;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends ListActivity {

    /** Items entered by the user is stored in this ArrayList variable */
    ArrayList list = new ArrayList();

    /** Declaring an ArrayAdapter to set items to ListView */
    ArrayAdapter adapter;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        /** Setting a custom layout for the list activity */
        setContentView(R.layout.main);

        /** Reference to the add button of the layout main.xml */
        Button btn = (Button) findViewById(R.id.btnAdd);

        /** Reference to the delete button of the layout main.xml */
        Button btnDel = (Button) findViewById(R.id.btnDel);

        /** Defining the ArrayAdapter to set items to ListView */
        adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_multiple_choice, list);

        /** Defining a click event listener for the button "Add" */
        OnClickListener listener = new OnClickListener() {
            @Override
            public void onClick(View v) {
                EditText edit = (EditText) findViewById(R.id.txtItem);
                list.add(edit.getText().toString());
                edit.setText("");
                adapter.notifyDataSetChanged();
            }
        };

        /** Defining a click event listener for the button "Delete" */
        OnClickListener listenerDel = new OnClickListener() {
            @Override
            public void onClick(View v) {
                /** Getting the checked items from the listview */
                SparseBooleanArray checkedItemPositions = getListView().getCheckedItemPositions();
                int itemCount = getListView().getCount();

                for(int i=itemCount-1; i >= 0; i--){
                    if(checkedItemPositions.get(i)){
                        adapter.remove(list.get(i));
                    }
                }
                checkedItemPositions.clear();
                adapter.notifyDataSetChanged();
            }
        };

        /** Setting the event listener for the add button */
        btn.setOnClickListener(listener);

        /** Setting the event listener for the delete button */
        btnDel.setOnClickListener(listenerDel);

        /** Setting the adapter to the ListView */
        setListAdapter(adapter);
    }
}

7. Execute the application

 

Application in execution

Figure 4: Application in execution


8. Download source code


9. Reference

http://developer.android.com/guide/index.html


How to hire me?

I am George Mathew, working as software architect and Android app developer at wptrafficanalyzer.in

You can hire me on hourly basis or on project basis for Android applications development.

For hiring me, please mail your requirements to info@wptrafficanalyzer.in.

My other blogs
store4js.blogspot.com


Android Knowledge Quiz

Ready to test your knowledge in Android? Take this quiz :



Tags: , , ,

16 Responses to Deleting Selected Items from ListView in Android

  1. Shikha on September 11, 2012 at 7:44 pm

    Thanks a Lot!!!!!..I was looking for some simple method to delete listview item and I found yours…Its great and easy to implement..Thanks again!!

  2. vsk on September 24, 2012 at 12:02 pm

    its easy and works fine. but how it add check box to listview row. pls explain.

    • george on September 24, 2012 at 12:24 pm

      See the line android:choiceMode=”multipleChoice” in the layout file res/layout/main.xml

  3. mharby on October 4, 2012 at 1:10 am

    Finally, found a simple tutorial for a simple question. :)

  4. sudha on October 22, 2012 at 11:50 am

    i want delete particular item in listview. and i got list view form database. how can i do this?
    please help me…

  5. Steve on November 14, 2012 at 1:58 am

    Nice work.

  6. JB on November 29, 2012 at 2:20 pm

    Thank you for your work!

    Works perfect!!

  7. Sam on December 31, 2012 at 6:43 pm

    Hey the checks on the views remain despite of the removal of views. Didnt any one notice that?

  8. Michael on January 10, 2013 at 10:22 am

    Thanks for the tutorial. As Sam noticed, the checkmarks don’t disappear. This line needs to be added

    checkedItemPositions.clear();

    It goes in the listenerDel function, right at the end above adapter.notifyDataSetChanged();

    • george on January 10, 2013 at 11:41 am

      Thank you Michael.

      The program is updated by adding the line :

      checkedItemPositions.clear();

  9. Anuj on January 17, 2013 at 3:50 pm

    Thanks… Great Tutorial… Keep Posting… God bless u :)

  10. rajiv on March 6, 2013 at 3:37 pm

    Thanks……Very Simple and effective coding

  11. George on March 18, 2013 at 11:25 pm

    Hello and thanks for these posts!
    I wanted to ask in the above example how can someone add more fields.I mean , to have a list view which in a row will have for example a Name (textview) ,a surname (textview),an edittext (where he can enter some amount),etc.

    I can’t figure how to use the add and delete buttons (in order to add/delete all the above) in such a case.I want the user to be able to add/delete all the information.

    Thanks!

  12. ana on April 30, 2013 at 11:44 pm

    hello sir id error?? what can i do? btnadd,btndel or textitem??? plz rply?

  13. ana on May 1, 2013 at 2:49 pm

    sir string.xml error???

        ListViewDeleteItems
        Enter an item here …
        Add Item
        List is empty
        Delete Selected Items

    dntknw error?

  14. Marlene Duncan on December 29, 2013 at 10:12 am

    Hi,
    I just found this article and it was just what I needed. Works great! Need to be able to save these changes. How can I do this?
    Marlene

Leave a Reply

Your email address will not be published. Required fields are marked *

Be friend at g+

Subscribe for Lastest Updates

FBFPowered by ®Google Feedburner