Question

I am just learning SQL on android and following a tutorial here. Thinks are working fine which are mentioned in tutorial. But I want to use update and delete operation. For this I am using this code. For delete

Contact contact = (Contact)db.getContact(2);
db.deleteContact(contact);
Log.d("Delete", "Contact Deleted");

This function delete all contacts from contacts table. While I want to delete only contact having ID=1

For update

Log.d("Update Contact", "Updating Contact...");
Contact contact = (Contact)db.getContact(2);
contact.setName("Updated Name");
contact.setPhoneNumber("333444");
db.updateContact(contact);

And this code updates all contacts in database with "Updated Name". However I want to update only the contact having ID 2. Am I doing something wrong.

Delete function in DatabaseHandler.java

public void deleteContact(Contact contact){
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_CONTACTS, KEY_ID+"+?", new String[]{String.valueOf(contact.getID())});
db.close();
}

and Update Function is

public int updateContact(Contact contact){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME,contact.getName());
values.put(KEY_PH_NO, contact.getPhoneNumber());
return db.update(TABLE_CONTACTS, values, KEY_ID+"+?", new String [] String.valueOf(contact.getID())});
    }
Was it helpful?

Solution

in your deleteContact method change:

db.delete(TABLE_CONTACTS, KEY_ID+"+?"

to:

db.delete(TABLE_CONTACTS, KEY_ID+"=?"

and in your updateContact change:

return db.update(TABLE_CONTACTS, values, KEY_ID+"+?", new String [] String.valueOf(contact.getID())});

to:

return db.update(TABLE_CONTACTS, values, KEY_ID+"=?", new String []{ String.valueOf(contact.getID())});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top