Delete data from SQLite database

In this tutorial, we’ll explore the process of deleting data from an SQLite database, building on our previous lesson where we covered updating data in the database. Specifically, we’ll focus on enhancing our Phone Book app by adding functionality to delete contact numbers. In our prior tutorial, we implemented a popup triggered by clicking a list item, offering two choices: update and delete. In this tutorial, we’ll guide you through the steps to delete a contact when the user selects the delete option. Let’s dive into the process of efficiently managing and modifying your SQLite database.

To initiate the deletion of data, our first step involves introducing a new method named deleteData() within the DatabaseHelper class. This method serves as a crucial component in our process of removing specific records from the database. Take a look at the following code snippet to integrate this functionality into your application.

DatabaseHelper Class Code:

public class DatabaseHelper extends SQLiteOpenHelper {

    //writing database name
    private static final String DATABASE_NAME = "PhoneBook.db";
    //writing table name
    private static final String TABLE_NAME = "Contacts_Table";


    //Constructor here
    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, 1);
    }


    //On create and onUpgrade these two are abstract methods in SQLiteOpenHelper class
    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {

        //use this execSQL method to create new table in database
        sqLiteDatabase.execSQL("CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT , CONTACT TEXT )");
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

    }


    //Creating this method to insert data in table
    public boolean insertData(String name, String contact) {

        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues cv = new ContentValues();
        cv.put("NAME", name);
        cv.put("CONTACT", contact);

        long result = db.insert(TABLE_NAME, null, cv);

        if (result == -1) {
            return false;

        } else {
            return true;
        }
    }


    //Method to get data from SQLite database
    public Cursor getData() {
        SQLiteDatabase db = this.getWritableDatabase();
        String query = "SELECT * FROM " + TABLE_NAME;
        Cursor cursor = db.rawQuery(query, null);
        return cursor;
    }

    //Method to update data in SQLite database
    public int updateData(int id, String name, String contact) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put("NAME", name);
        contentValues.put("CONTACT", contact);
        int i = db.update(TABLE_NAME, contentValues, "ID =" + id, null);
        return i;
    }

    //Method to delete data from SQLite database
    public int deleteData(int id) {
        SQLiteDatabase db = this.getWritableDatabase();
        int i = db.delete(TABLE_NAME, "ID ="+id, null);
        db.close();
        return i;
    }
}

Following the implementation of the deleteData() method in our DatabaseHelper class, the subsequent action involves invoking this method in our main class when the user opts for the delete option within the popup. Please check out the provided code snippet to integrate this functionality into your main class.

MainActivity Java Code:

public class MainActivity extends AppCompatActivity {

    ListView listView;
    DatabaseHelper databaseHelper;
    List<contactmodel> contactList=new ArrayList<contactmodel>();
    int i=0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView = (ListView) findViewById(R.id.listView);

        databaseHelper = new DatabaseHelper(getApplicationContext());

        Cursor cursor = databaseHelper.getData();

        String namesArray[] = new String[cursor.getCount()];

        while (cursor.moveToNext()) {
            namesArray[i] = cursor.getString(cursor.getColumnIndex("NAME"));
            contactList.add(new ContactModel(cursor.getInt(cursor.getColumnIndex("ID")),cursor.getString(cursor.getColumnIndex("NAME")),cursor.getString(cursor.getColumnIndex("CONTACT"))));
            i++;
        }

        ArrayAdapter<string> arrayAdapter = new ArrayAdapter<>(getApplication(), android.R.layout.simple_list_item_1, namesArray);
        listView.setAdapter(arrayAdapter);


        listView.setOnItemClickListener(new ListView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<!--?--> adapterView, View view,final int i, long l) {
                PopupMenu popup = new PopupMenu(getApplicationContext(), view);
                MenuInflater inflater = popup.getMenuInflater();
                inflater.inflate(R.menu.popup_menu, popup.getMenu());


                popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                    public boolean onMenuItemClick(MenuItem item) {
                       switch (item.getItemId()){
                           case R.id.update:
                               Intent intent=new Intent(getApplicationContext(),UpdateContact.class);
                               intent.putExtra("ID",contactList.get(i).getId());
                               intent.putExtra("NAME",contactList.get(i).getName());
                               intent.putExtra("CONTACT",contactList.get(i).getNumber());
                               startActivity(intent);
                               break;
                           case R.id.delete:
                               databaseHelper.deleteData(contactList.get(i).getId());
                               break;
                       }

                       return true;
                    }
                });
                popup.show();
            }
        });

    }

}
Spread the love
Scroll to Top
×