Why / Should we use BaseColumns when using the Content Provider in Android?

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

public static class Blocks implements BlocksColumns, BaseColumns .

As far as I know BaseColumns is just an interface with two constants: _COUNT and _ID .

I have two questions:

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

  • What is the role of the _COUNT constant?

+14
android android-contentprovider
Jul 22 '11 at 15:46
source share
2 answers

According to the Android Developer's Guide ,

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

The manual continues to explain why you need the unique value provided by the primary key ,

Table data should always have a primary key column, which the provider maintains as a unique numeric value for each row. You can use this value to bind a 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 the query provider in the ListView requires that one of the extracted columns have the name _ID. [emphasis mine]

To answer your questions in the order you submitted them:

  • Having a _ID column is best practice for versatility. It should not be displayed, but works fine as a primary key (and foreign key!). Required for cursors and queries.
    • By defining it using BaseColumns, it automatically identifies this column as a primary key, unique (obviously), and instructs its auto-increment.
    • Presumably, implementing BaseColumn is easier than printing these properties for your private fields.
  • _COUNT is just the number of lines in the directory. If your table rows are deleted and added, there is no reason to believe that the _ID integer element has anything to do with when it was added, or its sorting properties. In other words, last_insert_rowid() NOT EQUAL Count() . The _COUNT column simply provides a way to show how many results are returned in the query, EVERY LINE of this query. For a visual link, see linuxtopia.org
+22
Oct 18 :
source share

There is no real reason to use it ... you can completely ignore it and use your own _ID and _COUNT (if you need to) ...

-2
Jan 18 2018-12-18T00:
source share



All Articles