mardi 3 mars 2015

Adding and updating details to SQLite database

I have two methods in MyDBHandler class, one for adding details and one for updating details. The user fills in a form and their details are added to the database and outputed as a listView. I want the user to be able to fill in the same form again to update their details. My problem is that when I first install the app then there are no records to update so I have to use the addDetails method which keeps adding new rows into the database when what I want to do is update the details using the updateDetails method. I can't update the details if there is nothing to update when the app is first installed.


addDetails Method



//Add a new row to the database
public void addDetails(Details details) {
ContentValues values = new ContentValues();

values.put(COLUMN_FIRSTNAME, details.getFirstname());
values.put(COLUMN_SURNAME, details.getSurname());
values.put(COLUMN_PHONE, details.getPhone());
values.put(COLUMN_EMAIL, details.getEmail());
values.put(COLUMN_ADDRESS1, details.getAddress1());
values.put(COLUMN_ADDRESS2, details.getAddress2());

SQLiteDatabase db = getWritableDatabase();
db.insert(TABLE_DETAILS, null, values);
db.close();
}


updateDetails method



//Updates user details
public void updateDetails(Details details){
ContentValues values = new ContentValues();

//Take new values from the details object provided
values.put(COLUMN_FIRSTNAME, details.getFirstname());
values.put(COLUMN_SURNAME, details.getSurname());
values.put(COLUMN_PHONE, details.getPhone());
values.put(COLUMN_EMAIL, details.getEmail());
values.put(COLUMN_ADDRESS1, details.getAddress1());
values.put(COLUMN_ADDRESS2, details.getAddress2());

SQLiteDatabase db = this.getWritableDatabase();

//Update the details object where id matches
db.update(TABLE_DETAILS, values, COLUMN_ID + "='" + details._id + "'", null);


db.close();

}

Aucun commentaire:

Enregistrer un commentaire