Android Contentprovider - 在插入方法中更新

发布于 2024-10-04 23:22:39 字数 83 浏览 0 评论 0原文

是否可以在内容提供程序的 insert() 重写方法中调用 SQLiteDatabase 更新方法?

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

瑾夏年华 2024-10-11 23:22:39

基本上没问题,但由于您没有提供代码,我只能发布两种可能的方法:

第一:

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

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

第二:

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

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

查看 SQLiteDatabase 以供第四个参数参考。在大多数情况下,最后一个方法应该足够了,除非您希望在行存在时仅更新某些字段,而在行不存在时则更新所有字段。

insertWithOnConflict 最有用的需求可能是,您可以插入一行,如果它已经存在,则忽略插入并返回已存在行的 Uri/主键。

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.

千鲤 2024-10-11 23:22:39

您可以选择在重写的方法中编写什么内容。
所以是的,没关系。

我不知道您想做什么,但您可能也想看看 SQLiteDatabasereplace() 方法。也许它更适合您的需求。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文