What is the use of BaseColumns in Android?

What is the use of a class from BaseColumns in Android?

+46
java android database sqlite
Oct. 26 '11 at 7:17
source share
3 answers

This is a simple interface that adds two fields:

 public interface BaseColumns { /** * The unique ID for a row. * <P>Type: INTEGER (long)</P> */ public static final String _ID = "_id"; /** * The count of rows in a directory. * <P>Type: INTEGER</P> */ public static final String _COUNT = "_count"; } 

The internal sqlite databases used in Android come with a _id column that auto-increments and can function as a primary key. It is also well displayed using ContentProviders

+34
Oct 26 2018-11-11T00: 00Z
source share

The BaseColumns interface provides names for the very common _ID and _COUNT .

Using common names allows the Android platform (and developers) to access any data item, regardless of the general structure (i.e. other columns without an identifier) ​​in a unified way. Defining constants for commonly used strings in an interface / class avoids duplication and typos throughout the code.

Using a column named _ID (constant BaseColumns._ID ) is required by CursorAdapter , the implementation of ContentProvider and in other places where you pass Cursor to the Android platform to do something for you. For example, the ListView adapter uses the _ID column to give you a unique identifier for the list item clicked in OnItemClickListener.onItemClick() , without having to explicitly indicate that your identifier column each time.

Regardless of whether interfaces consisting only of constants or reference with their full name are implemented, i.e. BaseColumns._ID . I personally prefer the latter because it is more obvious where the _ID comes from, and the former seems to be an abuse of inheritance.

+63
Oct 26 '11 at 8:56
source share

The BaseColumn interface provides the column names _ID and _COUNT. You must specify the columns that use them when building tables. For example, to create a column with column name _ID, you can do the following:

 public static final String CREATE_TABLE = "CREATE TABLE IF NOT EXISTS " + TABLE_NAME + " (" + _ID + " INTEGER PRIMARY KEY, " + USERNAME + " TEXT NOT NULL, " + PASSWORD + " TEXT NOT NULL, " + EMAIL + " TEXT NOT NULL UNIQUE)"; 
+1
Apr 01 '17 at 16:44
source share



All Articles