Erorr when inserting a data. sqlite.SQLiteConstraintException: UNIQUE constraint failed: tags.name

0

I have the following table which contains tag names (tags) and an identifier for each:

public static final String TABLE_CREATE_TAGS =
        "CREATE TABLE " + TABLE_TAGS + " (" +
                COLUMN_TAG_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "+
                COLUMN_TAG_NAME + " TEXT UNIQUE "+
                ")";

I just want to insert labels that are not in base de datos . So if I receive a -1 at the time of making the insert I collect the id of the tag.

The app does not hang and everything works correctly but in the log I get an error.

The insert I do it in the following way:

ContentValues values = new ContentValues();
values.put(DatabaseHelper.COLUMN_TAG_NAME, tag);

// insert row
long id = database.insert(DatabaseHelper.TABLE_TAGS, null, values);

if(id == -1){ // El tag ya existe. Tenemos que pillar su verdadero id
   id = getTagId(tag);
 }

The error:

android.database.sqlite.SQLiteConstraintException: UNIQUE constraint failed: tags.name (code 2067)
    
asked by aldakur 02.02.2017 в 13:33
source

1 answer

1

You have defined the name field as unique, even if you change the value of the Id field, if you do not modify the name it will continue giving an error if you insert it twice.

The correct way to make the insert is to check beforehand if it exists or not.

            ContentValues values = new ContentValues();
            values.put(DatabaseHelper.COLUMN_TAG_NAME, tag);
            if(existTag(tag)){ // El tag ya existe. Tenemos que pillar su verdadero id
                id = getTagId(tag);

            }else{
                // insert row
                id = database.insert(DatabaseHelper.TABLE_TAGS, null, values);
            }
            tagsIdsList.add(id); 

The method existTag :

public boolean existTag(String tag){
    Cursor cursor = database.query(DatabaseHelper.TABLE_TAGS, idColumnsTags, "name=?", new String[]  { tag }, null, null, null);
    return (cursor.getCount() >0);
}
    
answered by 02.02.2017 / 14:00
source