I have looked through several sites for any useful documentation and have come up empty. The flow charts from the official site might as well be greek and examples I have attempted from other relevant posts on this site have gotten me errors. I am writing a simple app to place user input in a database, however I need a combination of 2 columns to be unique. From what I have seen this can be accomplished with UNIQUE or PRIMARY KEY. I also need some way of capturing the error to Toast the user that their input is faulty. I know that I can do this in the Java side easily enough yet I would prefer not to loop through the table on every proposed insert.
This is what I have so far:
db.execSQL("CREATE TABLE inventory (category TEXT, itemNum TEXT, quantity INTEGER, price REAL, image INTEGER, UNIQUE(category, itemNum) ON CONFLICT FAIL;");
The table constructed properly until I added UNIQUE...
Which threw: ERROR/SQLiteOpenHelper(1037): android.database.sqlite.SQLiteException: near ";": syntax error: CREATE TABLE inventory (category TEXT, itemNum TEXT, quantity INTEGER, price REAL, image INTEGER, CONSTRAINT unq UNIQUE(category, itemNum) ON CONFLICT FAIL;
EDIT:
... fill ContentValues values with user input.
try{
db.getWritableDatabase().insert(DatabaseHelper.TABLE_NAME, DatabaseHelper.CATEGORY, values);
fillItemNumbers(); // Updates screen
}
catch(SQLiteConstraintException e)
{
Toast
.makeText(this, "User error",Toast.LENGTH_LONG)
.show();
}
You have mismatched parenthesis. There should be another ) after FAIL.
Once you've sorted that, you can catch the exception that happens when the constraint is breached.
try {
// insert new data
} catch (SQLiteConstraintException e) {
Toast.makeText(context,
"The combination of A and B must be unique",
Toast.LENGTH_LONG).show();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With