1

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();
    }
2
  • 1
    Your catch is not working ? Did you see "caught" on the logs ? Commented Nov 11, 2015 at 20:23
  • Yes I see Caught too Commented Nov 11, 2015 at 22:05

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Can you please give an example ??
No because I've never used it before - I simply read the documentation which, if you click on the link, you can see for yourself. It uses exactly the same parameters as the insertOrThrow(...) method you are using but with the extra conflictAlgorithm parameter. I've explained that CONFLICT_IGNORE simply ignores the existing row and that CONFLICT_UPDATE will update it. Use whichever one you need to achieve whatever result you want - either way, it won't throw an exception.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.