I have the following table which contains tag names and an identifier for each one:
public static final String TABLE_CREATE_TAGS =
"CREATE TABLE " + TABLE_TAGS + " (" +
COLUMN_TAG_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "+
COLUMN_TAG_NAME + " TEXT UNIQUE "+
")";
I only want to insert tags that are not in the base de datos
. That's why if I receive one -1
at the time of making the insert
pick up the one id
on the label.
The app does not hang and everything works correctly but log
I receive an error.
I do the insert as follows:
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)
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 to give an error if you insert it twice.
The correct way to perform the insert is checking first if it exists or not.
The method
existTag
: