How to prevent to insert duplicate value in sqlite database (if duplicate then overwrite)

Put all your values inside ContentValues and then call this on writableDatabase

db.insertWithOnConflict(tableName, null, contentValues,SQLiteDatabase.CONFLICT_REPLACE);

EDIT:

Well all you need is only this part of code

    SQLiteDatabase db;
    long rows = 0;
    db = this.getWritableDatabase(); 
    ContentValues Val = new ContentValues();
    Val.put("IDD", idd); 
    Val.put("Category", cat);
    rows = db.insertWithOnConflict(tableName, null, contentValues,SQLiteDatabase.CONFLICT_REPLACE);

insertWithOnConflict methods follows the last parameter as the reaction algorithm when an duplicate row is Found. And for a duplicate row to be found, the primary keys has to clash. If all this satisfys the row would surely get Replaced :-/ If not something else is going wrong..


While creating your table, put constraint on your column(Primary key or Unique key).This will not only the duplicate value to be inserted into your database.

Tags:

Sqlite

Android