Search code examples
javaandroidsqliteandroid-sqlite

SQLite saving duplicate item


I have a SQLite database in my app. I'm trying to save some records in my database but query saving duplicate items.

Code:

public void addValue(String userid, String fullname, String username) {
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_NAME +" WHERE userid="+userid+"", null);
    if (!cursor.moveToFirst()) {
        db.beginTransaction();
        try {
            ContentValues values = new ContentValues();
            values.put(USERID, userid);
            values.put(FULLNAME, fullname);
            values.put(USERNAME, username);
            db.insert(TABLE_NAME, null, values);
            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();
        }
    }else{
        System.out.println("This exist: "+userid+" "+fullname);
    }
    cursor.close();
    db.close();
}

Normally I check dublicate items with db.rawQuery("SELECT * FROM " + TABLE_NAME +" WHERE userid="+userid+"", null); query but still is saving.

What is wrong here? Thanks.


Solution

  • You have not posted the definition statement of the table but since you are querying to check if the userid exists already before inserting the new row I assume that the column userid is not UNIQUE as it should.
    Save yourself all that trouble and define it as UNIQUE by adding to the column definition the keyword UNIQUE:

    CREATE TABLE table_name(
        ...,
        userid TEXT UNIQUE,
        ...
    );
    

    Now you can use the method insert() without prior checking anything:

    int result = db.insert(TABLE_NAME, null, values);
    if (result == -1) {
        System.out.println("This exist: "+userid+" "+fullname);
    }
    

    If insert() returns -1 this means that it failed and you know that since there are not any other constraints that it failed because the userid already exists.
    Any other value returned by insert() (is equal to the rowid of the new inserted row) indicates that it succeeded.
    If you decide to make that change you will have to uninstall the app from the device and rerun so the database is recreated, or upgrade the version of the database.