Android Contentprovider - update within an insert method
Asked Answered
D

2

11

Is it ok to call the SQLiteDatabase update method in the insert() overridden method of a content provider?

Dorsoventral answered 26/11, 2010 at 12:26 Comment(0)
R
26

Basically it's fine, but since you didn't provided code, I just can post 2 possible ways for it

First:

// In your content provider
public Uri insert(...) {
    long insertId = db.insert(...);

    if(insertId == -1) {
        // insert failed, do update
        db.update(...);
    }
}

Second:

public Uri insert(...) {
    long insertId = db.insertWithOnConflict(table, null, values, SQLiteDatabase.CONFLICT_REPLACE)

    if(insertId == -1) {
        // insert and update/replace failed
    }
}

Check out SQLiteDatabase for reference on the forth parameter. In most cases the last method should be sufficient, unless you want only certain fields being updated if the row exists and have all fields if it doesn't.

Most useful need for insertWithOnConflict may be, that you could insert a row and if it already exists, ignore the insert and instead return the Uri/primary key of the already existing row.

Reinaldo answered 26/11, 2010 at 14:7 Comment(0)
H
5

It's your choice what you write in your overridden methods. So yes, it is ok.

I don't know what you're trying to do, but you might want to to take a look on the SQLiteDatabase's replace() method too. Maybe it better suits your needs.

Holtz answered 26/11, 2010 at 12:39 Comment(2)
ok my problem is that i need to check if a row exists that have a certain value in column A (A is not the unique key). If yes i need to update this row.Dorsoventral
You have 2 ways to do that: 1. replace (if the row does not exists, it inserts it; if it exists, it deletes it and inserts the new one); 2. try to insert the row... if not succeeded (meaning the row already exists), update it. So if you need something from the old row (like a certain column value), use insert+update. If not, use replace (you will lose all the data from the old row).Holtz

© 2022 - 2024 — McMap. All rights reserved.