一,自定义内容提供者 (查询单个)
1,写一个MyContentProvider类,继承Contentprovider,实现ContentProvider中的方法
@Override
public boolean onCreate() {
Log.i("test","onCreate");
DbUtil dbUtil = new DbUtil(getContext(), "数据库名", null, 2);
db = dbUtil.getReadableDatabase();
}
@Nullable
@Override
public Cursor query(Uri uri, String[] strings, String s, String[] strings1, String s1) {
return db.query(false,"表名",strings,s,strings1,null,null,s1,null);
}
2,在配置文件中配置基本属性
com.example.android_contentprovider01_PERSON"
android:name="provider.MyContentProvider"
android:exported="true"
>
3,内容访问者
获得内容访问者
ContentResolver cr=getContentResoler();
public void getdata(View view){
Uri uri = Uri.parse("content://包名");
//调用MyContentProvider中的方法
Cursor cursor=cr.query(uri,null,null,null,null);
while (cursor.moveToNext()){
int id=cursor.getInt(cursor.getColumnIndex("_id"));
String name=cursor.getString(cursor.getColumnIndex("name"));
int age=cursor.getInt(cursor.getColumnIndex("age"));
Log.i("test",id+" "+name+" "+age);
}
二.,自定义内容提供者(查询单个使用URI匹配器)
//MyContentProvider类中
@Override
public boolean onCreate() {
Log.i("test","onCreate");
DbUtil dbUtil = new DbUtil(getContext(), "数据库名", null, 2);
db = dbUtil.getReadableDatabase();
//实例化URI匹配器
uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
//添加规则
//01.查询所有
uriMatcher.addURI("包名","aa",1);
//02.查询单个
uriMatcher.addURI("包名","aa/#",2);
return false;
}
@Nullable
@Override
public Cursor query(Uri uri, String[] strings, String s, String[] strings1, String s1) {
//根据URI匹配器开始匹配Uri
int code=uriMatcher.match(uri);
switch (code) {
case 1:
//查询所有
Log.i("test","query所有");
//获取数据库中所有的数据
return db.query(false,"aa",strings,s,strings1,null,null,s1,null);
case 2:
//查询单个
//获取# 的值
long id=ContentUris.parseId(uri);
Log.i("test","query单个");
return db.rawQuery("select * from aa where _id=?",new String[]{id+""});
}
return null;
}
//内容访问者类中
public void getdata(View view){
//判断输入框的值是否为空
if(TextUtils.isEmpty(et_main_id.getText().toString())){
uri = Uri.parse("content://包名/aa);
}else{
//查询单个
//1.直接query传参
//2.类似web http://localhost:8080/webProject/xxx.action?id=3
//3.Uri匹配器
String id=et_main_id.getText().toString();
uri = Uri.parse("content://包名/aa#/"+id);
}
Cursor cursor=cr.query(uri,null,null,null,null);
//SimleCursorAdapter
while (cursor.moveToNext()){
int id=cursor.getInt(cursor.getColumnIndex("_id"));
String name=cursor.getString(cursor.getColumnIndex("name"));
int age=cursor.getInt(cursor.getColumnIndex("age"));
Log.i("test",id+" "+name+" "+age);
}
}
}