Android Contentprovider - update within an insert method

空扰寡人 提交于 2019-11-29 18:04:35

问题


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


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/4285266/android-contentprovider-update-within-an-insert-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!