Reputation: 3063
im using greenDAO to generate my DAO classes, everything works fine till i try to insert duplicated values for primary key.
It fails when i try to insert duplicated primery key (as expected), but i would like to send the exception to the user and not o explode with the app.
For now the only solution i have, and i think its not the best, is to do a query before insert, and check if the result count is greater than 0 or not.
There is a better way to do it?
the method .insert returns a Long value, but when it fails to insert it doesn't return anything, just explodes with the app.
Upvotes: 0
Views: 1350
Reputation: 5345
Surround your insert-statement with a try-catch-block
try {
dao.insert (entity);
} catch (Exception ex) {
// Do your handling here
} catch (Error e) {
// and here
}
Upvotes: 1
Reputation: 7860
Best would be to keep your primary key incremental away from what the user supplies as a key. However that is my personal choice, but aids when I have to check the last inserted ID, Ill do something like:
public int getPrimaryId() {
final String MY_QUERY = "SELECT MAX(_id) FROM " + DATABASE_TABLE0;
Cursor cur = mDb.rawQuery(MY_QUERY, null);
cur.moveToFirst();
int ID = cur.getInt(0);
cur.close();
return ID;
}
In your case you can preload an array list with primaryID's once user supplies a new key just check it with the elements in the arraylist. Faster!
SELECT EXISTS(SELECT 1 FROM myTbl WHERE ID="anyID" LIMIT 1);
The LIMIT will ensure that once found there is no need to go further. This would be super fast. Plus Exists will always return a result.
Also suggested would be the use of proper indexes
Upvotes: 1
Reputation: 3063
I thought it would be another way to control it, but i found my way without doing this SELECT. Here are two solutions:
With SELECT (proposed by other user on this post - check it for more details)
public int getPrimaryId() {
final String MY_QUERY = "SELECT MAX(_id) FROM " + DATABASE_TABLE0;
Cursor cur = mDb.rawQuery(MY_QUERY, null);
cur.moveToFirst();
int ID = cur.getInt(0);
cur.close();
return ID;
}
Override method
Override .insert() method, inside myObjectDAO.java
@Override public long insert(Stud_Course entity) { long ret = 0; try { ret = super.insert(entity); } catch (Exception e) { ret = 0; Log.e("LOG", "fail to insert!!!"); } return ret; }
Upvotes: 0