Delete data from SQLite database


In this tutorial, we will learn about how to delete data from SQLite database. In the last tutorial, we have learned how to update data in the SQLite database in this tutorial we will continue with the same Phone Book app and we will delete contact number. In the last tutorial, we have generated a popup on click of the list item with two options update and delete. Here we will delete contact when somebody will click on the delete option

First of all, we will write add a new method called deleteData() in DatabaseHelper class which will help us to delete data. Check this code.

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;
    }
}

After this, our next step will be to call this method in our main class when user will select delete option from popup. Check this code.

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:

Please share this page on social media with your friends..

Facebook share Twitter Linkedin share




Great News! Now you can read all the tutorials on our Android App..

Download Owlbuddy: Learn Programming Tutorials App Now.

Download Owlbuddy: Learn Programming Tutorials