开发者

Why/Should we implement BaseColumns when using a Content Provider in Android?

开发者 https://www.devze.com 2023-03-22 12:03 出处:网络
I was browsing the source code for Google IOSched App and noticed the following code snippet as part of their Content Provider implementation:

I was browsing the source code for Google IOSched App and noticed the following code snippet as part of their Content Provider implementation:

public static class Blocks implements BlocksColumns, BaseColumns.

As far as I know BaseColumns is simply an interface to two constants: _COUNT and 开发者_C百科_ID.

I have two questions:

  1. What are the advantages/disadvantages of the implementing BaseColumns as opposed to having a private field _ID in the class directly?

  2. What is the role of the constant _COUNT?


According to the Android Developer Guide,

Note: A provider isn't required to have a primary key, and it isn't required to use _ID as the column name of a primary key if one is present. However, if you want to bind data from a provider to a ListView, one of the column names has to be _ID. This requirement is explained in more detail in the section Displaying query results.

The Guide continues on to explain the basics of why you need a unique value provided by the primary key,

Table data should always have a "primary key" column that the provider maintains as a unique numeric value for each row. You can use this value to link the row to related rows in other tables (using it as a "foreign key"). Although you can use any name for this column, using BaseColumns._ID is the best choice, because linking the results of a provider query to a ListView requires one of the retrieved columns to have the name _ID. [emphasis mine]

To answer your questions in the order that you provided them:

  1. Having the _ID Column is a best practice for versatility. It doesn't have to be displayed, but works terrific as the primary key (and foreign key!) Required for cursors and queries.
    • Having it identified by BaseColumns automatically identifies this column as the primary key, unique (obviously), and instructs it to autoincrement.
    • Presumably, implementing BaseColumns is easier than typing out these properties for your private fields.
  2. _COUNT is just the count of the number of rows in a directory. If your table's rows are being deleted and added, there is no reason to believe that an item's _ID integer has anything to do with when it was added or its sort properties. In other words, last_insert_rowid() DOES NOT EQUAL Count(). The _COUNT column just provides a way to show how many results are returned on a query, IN EVERY LINE of that query. For a visual reference, see linuxtopia.org


No real reason to use it...you can ignore it totally and use your own definitions of _ID and _COUNT (if u need)...

0

精彩评论

暂无评论...
验证码 换一张
取 消