[英]What is the use of BaseColumns in Android
在Android中使用BaseColumns
实现类有什么用?
The BaseColumns
interface provides names for the very common _ID
and _COUNT
columns. BaseColumns
接口提供了非常常见的_ID
和_COUNT
列的名称。
Using common names enables the Android platform (and developers as well) to address any data item, regardless of its overall structure (ie other, non-ID columns) in a unified way. 使用通用名称使Android平台(以及开发人员)能够以统一的方式处理任何数据项,而不管其整体结构(即其他非ID列)。 Defining constants for commonly used strings in an interface/class avoids repetition and typos all over the code.
为接口/类中常用字符串定义常量可以避免在整个代码中重复和拼写错误。
Using a column named _id
(the constant value of BaseColumns._ID
) is required by CursorAdapter
, implementations of a ContentProvider
and other places where you hand off a Cursor
to the Android platform to do things for you. CursorAdapter
需要使用名为_id
的列( BaseColumns._ID
的常量值), ContentProvider
实现以及将Cursor
BaseColumns._ID
给Android平台以便为您执行操作的其他位置。 For example, the adapter of a ListView
uses the _ID
column to give you the unique ID of the list item clicked in OnItemClickListener.onItemClick()
, without you having to explicitly specify what your ID column is every time. 例如,
ListView
的适配器使用_ID
OnItemClickListener.onItemClick()
您提供在OnItemClickListener.onItemClick()
单击的列表项的唯一ID,而无需每次都明确指定ID列。
Whether or not to implement interfaces consisting only of constants or reference them with their full name, ie BaseColumns._ID
is a matter of taste. 是否实现仅由常量组成的接口或以其全名引用它们,即
BaseColumns._ID
是一个品味问题。 I personally prefer the latter, because it's more obvious where _ID
is coming from and the former feels like an abuse of inheritance. 我个人更喜欢后者,因为
_ID
来自哪里更明显,前者感觉就像滥用继承。
This is a simple interface which 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";
}
Internally sqlite databases used in Android, comes with an _id
column that autoincrements and can function as a primary key. 在Android中使用的内部sqlite数据库附带一个自动增量的
_id
列,可以作为主键。 This also maps well with the ContentProviders
这也很好地映射了
ContentProviders
The BaseColumn interface only provides the column names _ID and _COUNT. BaseColumn接口仅提供列名 _ID和_COUNT。 You must still specify columns that use them when constructing tables.
在构造表时,您仍必须指定使用它们的列。 For example, to create a column using the column name _ID you might do the following:
例如,要使用列名_ID创建列,您可以执行以下操作:
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)";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.