自定义ContentProvider的简单例子
1、ContentProviderTestActivity 类中有2个按钮,分别插入数据为查询数据
2、DataBaseConfiguation 为程序所用到的配置信息 注:TableConfiguation内部类实现BaseColumns,即声明了_ID 和 _COUNT
3、MyContentProvider 自定义ContentProvider,继承与ContentProvider
其中 uriMatcher 为Uri的匹配器,在静态块中初始化URI。 columnMap为表结构的映射mapping
在getType方法中要根据访问的Uri确定访问资源的类型,以字符串形式返回。
格式为:"vnd.android.cursor.dir/vnd.catking.userList"、"vnd.android.cursor.item/vnd.catking.userItem";
注释掉,对程序运行无影响。
注意:
static{
? //初始化URI
??uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
??uriMatcher.addURI(DataBaseConfiguation.AUTHORITY, "user", USER_LIST_CODE);
??uriMatcher.addURI(DataBaseConfiguation.AUTHORITY, "user/#", USER_RECORD_CODE);
???红色字体中,的格式为xxx/xx,并不是/xxx/xx,其中*号匹配所有字符,#匹配所有数字
??//表结构的映射
??columnMap.put(DataBaseConfiguation.TableConfiguation._ID, DataBaseConfiguation.TableConfiguation._ID);
??columnMap.put(DataBaseConfiguation.TableConfiguation.USER_NAME, DataBaseConfiguation.TableConfiguation.USER_NAME);
?}
?
最后在AndroidManifest.xml里配上
<provider android:authorities="com.catking.contentprovider.MyContentProvider" android:name="com.catking.contentprovider.MyContentProvider" />
authorities的值必须与DataBaseConfiguation.AUTHORITY一致
?