views:

368

answers:

1

I have a database containing a userId and a note. The user doesn't know if there already is a note in the DB so they write one and click the 'Submit' button. I want to insert this note if there is no note for the userId or update that userId's already existing note:

                notesDb.open();
    boolean updateResult = notesDb.updateMessage(
      userId,
      details_notes_input.getText().toString());

    if(updateResult == true) {
     Log.d("databaseTester", "Updated entry into table");
    }
    else {
     Log.d("databaseTester", "FAILED to update entry into table");
     long insertResult = notesDb.insertMessage(
       userId,
       details_notes_input.getText().toString());
     if(insertResult == -1){
      Log.d("databaseTester", "Failed to insert entry into table");
     }
     else{
      Log.d("databaseTester", "Inserted entry into table");
     } 
    }
    notesDb.close();

So, I'm pretty much attempting to 'update' an entry and if I fail then I attempt to 'insert' it. I don't know SQL very well, but I would think there would be a better way. Thanks.

+3  A: 

It sounds like you could use sqlite's REPLACE to solve this problem, using SQLiteDatabase.replace().

Daniel Lew