简体   繁体   English

在Android中使用SQLite和ContentProvider设置_ID字段

[英]Setting the _ID field using SQLite & ContentProvider in Android

I'm trying to set up a ContentProvider in an Android app to hold information about houses. 我正在尝试在Android应用程序中设置ContentProvider来保存有关房屋的信息。 I'd like to be able to set the _ID field to be the same as the ID field in my external database (the program will sync the ContentProvider with this external database). 我希望能够将_ID字段设置为与我的外部数据库中的ID字段相同(该程序会将ContentProvider与此外部数据库同步)。

The reason for this is so I would like to be able to reference the ID like: 这样做的原因是这样,我希望能够像这样引用ID:

content://com.example.acme.propertyprovider/properties/23

where 23 is the same ID in both the external database and the internal database. 其中23是外部数据库和内部数据库中的相同ID。

The following just causes the error "android.database.SQLException: Failed to insert row into content://com.example.acme.propertyprovider/properties 以下内容仅会导致错误“ android.database.SQLException:无法将行插入到content://com.example.acme.propertyprovider/properties中

ContentValues values = new ContentValues();

values.put(Properties._ID, 23);
values.put(Properties.COLUMN_NAME_ROAD, "123 Sample Property");
values.put(Properties.COLUMN_NAME_RENT, 320);

getContentResolver().insert(Properties.CONTENT_URI, values);

You'd be better off setting a foreign key in the Android database to hold the id from your external database. 您最好在Android数据库中设置外键来保存外部数据库中的ID。 Then you don't have to worry about things getting out of sync. 然后,您不必担心事情会不同步。 Since the _ID fields are auto-incrementing you'll be creating a nightmare for yourself. 由于_ID字段是自动递增的,因此您将自己创建噩梦。

Add something like extHouse_id (or whatever). 添加类似extHouse_id的内容(或其他内容)。 That's a very common practice. 这是非常普遍的做法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM