0

I have an app which contain sqlite database and contact list from Mainactivity i have added contacts in arraylist and save it in sqlite database and fetch the same from sqlite database. But porblem is that i want to delete specific row from sqlite database using id. How do i do that

code of Mainactivity:-

    public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.main);



    DatabaseHandler db = new DatabaseHandler(this);



    /**

     * CRUD Operations

     * */

    // Inserting Contacts

    Log.d("Insert: ", "Inserting ..");

    db.addContact(new Contact("Ravi", "9100000000"));

    db.addContact(new Contact("Srinivas", "9199999999"));

    db.addContact(new Contact("Tommy", "9522222222"));

    db.addContact(new Contact("Karthik", "9533333333"));



    // Reading all contacts

    Log.d("Reading: ", "Reading all contacts..");

    List<Contact> contacts = db.getAllContacts();



    for (Contact cn : contacts) {

        String log = "Id: " + cn.getID() + " ,Name: " + cn.getName() + " ,Phone: " + cn.getPhoneNumber();

        // Writing Contacts to log

        Log.d("Name: ", log);

    }

}

specific funtion sqlite databas to delete contacts.

// Deleting single contact
public void deleteContact(Contact contact) {
    SQLiteDatabase db = this.getWritableDatabase();
    db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
            new String[] { String.valueOf(contact.getID()) });
    db.close();
}
Niraj
  • 31
  • 1
  • 10

1 Answers1

0

You can use this post or the below method to delete from your table.

public int delete(String tableName, String where) {
    SQLiteDatabase db = getWritableDB();
    int deletedVal = -1;
    try {
        deletedVal = db.delete(tableName, where, null);
    } catch (Exception e) {
        e.printStackTrace();
    }
    db.close();
    return deletedVal;
}

Considering you have a table column name "id", this is how you can call it.

delete(tableName,"id=1")
Aveek
  • 849
  • 1
  • 12
  • 28