为什么/应该在Android中使用Content Provider时实现BaseColumns? [英] Why/Should we implement BaseColumns when using a Content Provider in Android?

查看:92
本文介绍了为什么/应该在Android中使用Content Provider时实现BaseColumns?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在浏览Google IOSched 应用程序的源代码,并注意到以下代码片段为内容提供商实施的一部分:

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.

据我所知 BaseColumns 仅仅是两个接口常量:_COUNT_ID.

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

我有两个问题:

  1. 与直接在类中拥有私有字段_ID相比,实现BaseColumns有哪些优缺点?

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

常量_COUNT的作用是什么?

推荐答案

根据 Android开发人员指南

注意:不需要提供程序具有主键,也不是必需的. 如果使用_ID作为主键的列名,则要求 当下.但是,如果您要将数据从提供程序绑定到 ListView,列名之一必须是_ID.这个要求是 在显示查询结果部分中有更详细的说明.

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.

该指南继续说明了为什么您需要primary key提供的唯一值的基本知识,

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

表数据应始终具有提供商提供的主键"列 保持为每一行的唯一数值.你可以用这个 将该行链接到其他表中的相关行的值(将其用作 外键").尽管您可以为该列使用任何名称,但使用 BaseColumns._ID是最佳选择,因为链接的结果 对ListView的提供程序查询需要检索到的列之一 名称为_ID. [强调我的]

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. 具有_ID列是多功能的最佳实践.它不一定要显示,但是作为游标和查询所必需的主键(和外键!)非常有用.
    • 由BaseColumns标识它会自动将此列标识为唯一的主键(很明显),并指示其自动递增.
    • 大概,实现BaseColumns比为私有字段键入这些属性要容易.
  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.

这篇关于为什么/应该在Android中使用Content Provider时实现BaseColumns?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆