Stranger B.
Stranger B.

Reputation: 9364

Prevent inserting duplicate data in Sqlite Android

I want to prevent to insert a duplicated rows in SQLite, for that i'm using a unique attribute :

 @Override
    public void onCreate(SQLiteDatabase db) {

        String CREATETABLE = "CREATE TABLE contacts ( " +
                "id INTEGER PRIMARY KEY AUTOINCREMENT, " +
                "name TEXT, "+
                "profil TEXT, "+
                "phone TEXT UNIQUE ,"+
                "blocked TEXT, "+
                "show TEXT , "+
                "objectid TEXT )";

        db.execSQL(CREATETABLE);
    }

But when I'm inserting a row with a same phone, I have an error which appears in Log :

E/SQLiteLog: (2067) abort at 17 in [INSERT INTO contacts(phone,name,blocked,objectid,show,profil) VALUES (?,?,?,?,?,?)]: UNIQUE constraint failed: contacts.phone

Is that bad, any way to prevent that ?

 public void addcontact(contacts contact){



        SQLiteDatabase db = this.getWritableDatabase();


        ContentValues values = new ContentValues();
        values.put("name", contact.getName());
        values.put("phone", contact.getNumero());
        values.put("profil", contact.getProfil());
        values.put("show", contact.getShow());
        values.put("blocked", contact.getBlocked());
        values.put("objectid", contact.getObjectid());



        try {
            db.insertOrThrow("contacts",
                    null,
                    values);
        } catch(SQLiteException e) {
            Log.d("My App", "caught");

        }
        //db.close();
    }

Upvotes: 1

Views: 4408

Answers (1)

Squonk
Squonk

Reputation: 48871

If you simply want to prevent the error and effectively do nothing if the unique value already exists then use...

insertWithOnConflict (String table, String nullColumnHack, ContentValues initialValues, int conflictAlgorithm)

...and use CONFILCT_IGNORE for the conflictAlgorithm parameter.

If you actually want to update an existing row if it already exists, you can use the same method with CONFLICT_UPDATE instead.

Upvotes: 4

Related Questions