user3662946 user3662946 - 4 months ago 126
Android Question

prevent greenDAO inserting duplicate entry

I have an activity that will parse json data and update database using greenDAO once the activity start. It update code is like :


but when the activity back and resume, it will keep on insert causing duplicate data entry with different primary key but same data, how to prevent duplicate data entry?

Thanks alot


As you didn't provide a schema or similar information about your data model, this answer is only a guess!

Probably you are using autoincremented primary key.

This means your primary key is probably not included in your JSON data causing the primary key property to be null.

This tells greendao that this is a new entry and greendao will insert a new entry with a new primary key.

Try to read the object first and call then insertOrReplace:

Example oldObj;
try {
    // Try to find the Example-Object if it is already existing.
    oldObj = exampleDao.queryBuilder().where(someCondition).unique();
} catch (Exception ex) {
    oldObj = null;
if (oldObj == null) {
    oldObj = new Example();
// update oldObj with the data from JSON