11

I need to insert or update and I found the method insertWithOnConflict of the SQLiteDatabase, but I do not know how it checks if the entry already exists.

Theoretically I need a "Where" argument to check if a certain ID exists, and if so, it should replace all other columns.

This is what I have now, but I don´t think that the second argument is the unique id

    ContentValues args = new ContentValues();
    args.put(AppDatabase.COLUMN_ID, entry.getId());
    args.put(AppDatabase.COLUMN_NAME, entry.getAppname());
    args.put(AppDatabase.COLUMN_URL, entry.getAppUrl());
    database.insertWithOnConflict(AppDatabase.TABLE_FILELIST, COLUMN_ID, args, SQLiteDatabase.CONFLICT_REPLACE);

How can I manage this behaviour?

laalto
  • 150,114
  • 66
  • 286
  • 303
Marian Klühspies
  • 15,824
  • 16
  • 93
  • 136

1 Answers1

9
  1. Make sure you have some appropriate constraint in your table, such as PRIMARY KEY or UNIQUE.

  2. When inserting, add a value to this constrained column via ContentValues. If inserting the new row would violate some constraint, the conflicting rows are first deleted and then the new row is inserted.

In your case, COLUMN_ID looks like a good candidate for PRIMARY KEY constraint. The second arg nullColumnHack with value COLUMN_ID in your code is not necessary, you can pass it as null.

laalto
  • 150,114
  • 66
  • 286
  • 303
  • Thank you. I have declared my COLUMN_ID as the unique primary. If I understood you correctly, everything is fine then and the database will detect the insertion data as equal, if the primary key overlaps ,right? – Marian Klühspies Mar 25 '14 at 22:23
  • Equal in the sense that the unique column is equal. You can have non-equal values in other columns. You can try it out with a plain `insert()` without the `CONFLICT_REPLACE` - you should get an exception with "column ... is not unique" message. – laalto Mar 26 '14 at 06:18