一、ContentProvider
- URI的构成
- 用ContentProvider获取数据
- 自己创建ContentProvider
二、URI的构成
content://com.jty.test.provider/student
//协议声明:content//权限:包名.provider/路径:表名
然后调用Uri.prase("")解析成Uri
三、通过ContentProvider获取系统数据
首先通过getContentResolver获取ContentRelover对象,利用ContentResolver的insert、updata,delete、query方法进行增删改查,用法和SQLiteDataBase的增删改查很像
方法 | SQLiteDataBase | ContentResolver |
---|---|---|
insert | ("表名",空值的键,ContentValue的对象) | (Uri,ContentValue对象) |
delete | ("表名",约束条件,占位符值) | (Uri,约束条件,占位符值) |
update | ("表名",ContentValue对象,约束条件,占位符值) | (Uri,ContentValue对象,约束条件,占位符值) |
query | ("表名",列名,约束条件,占位符的值,分组的列名,分组筛选条件,排序方式) | (Uri,列名,约束条件,占位符的值,排序方式) |
电话联系人的表结构:Android 联系人数据库表详解
Android短信数据库结构:Android MMS模块数据存取
读取短信:android菜鸟学习笔记23----ContentProvider(三)利用内置ContentProvider监听短信及查看联系人
代码示例:
//ContactsContract.Contacts.CONTENT_URI这是访问的contacts表
//(ContactsContract.CommonDataKinds.Phone.CONTENT_URI
public class MainActivity extends AppCompatActivity {
ListView lv;
List list;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv=findViewById(R.id.lv);
list=new ArrayList<>();
}
public void click(View view){
if(Build.VERSION.SDK_INT>Build.VERSION_CODES.M){
if(ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.READ_CONTACTS)!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.READ_CONTACTS},1);
}else{
ContentResolver resolver=getContentResolver();
Uri uri=ContactsContract.Contacts.CONTENT_URI;
Cursor cursor=resolver.query(uri,null,null,null,null);
if(cursor!=null) {
while (cursor.moveToNext()) {
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
int id = cursor.getInt(cursor.getColumnIndex(ContactsContract.Contacts._ID));
Cursor cursor1 = resolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER}, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=?", new String[]{"" + id}, null);
if (cursor1!=null){
while (cursor1.moveToNext()){
String number=cursor1.getString(0);
list.add(name+":"+number);
}
}
}
}
ArrayAdapter adapter=new ArrayAdapter(this, android.R.layout.simple_list_item_1,list);
lv.setAdapter(adapter);
}
}
}
}
运行效果:
四、自己创建ContextProdiver
(1)UriMater类
- addURI方法,用来传入URI,它需要传入三个参数(权限,路径,自定义代码);
- match()用来匹配URI,接受一个Uri对象,返回值是能够匹配这个Uri对象的自定义代码,利用这个自定义代码可以判断出用户调用的是哪张表
(2)自定义ContentProvider类
需要实现六个抽象方法:
- onCreate
可以做一些初始化操作 - getType(Uri uri)
需要返回一个MIME字符串。一个URI对应的MIME分为三部分,三部分的格式规定:一、必须以vnd开头;二、如果Uri以路劲结尾,则后面接android.cursor.dir/,如果Uri以id结尾则后面接android.cursor.item/三、最后vnd.权限.路径
-insert
-query
-delete
-update
实现增删改查
如果要查询的是单条数据,调用Uri的getPathSegments()返回一个字符串列表,第0号位置为路径,第1号位置为id - 注册ContentProvider
authorities=权限
name=.名字
exported是否允许访问(true)
代码示例
自定义SqliteOpenHelper类
public class MyOpenHelper extends SQLiteOpenHelper {
public MyOpenHelper(Context context){
super(context,"students",null,1);
}
public void onCreate(SQLiteDatabase db){
db.execSQL("create table students(student_id Integer primary key autoincrement,student_name char(20),student_age Intenger)");
}
public void onUpgrade(SQLiteDatabase db,int oldVersion,int newVersion){
}
}
自定义ContentProvider类
public class MyContentProdiver extends ContentProvider {
private SQLiteOpenHelper helper;
public static UriMatcher matcher;
public static final int STUDENT_DIR=1;
public static final int STUDENT_ITEM=2;
public static final String AUTHORITY="com.jty.myapplication24.provider";
static{
matcher=new UriMatcher(UriMatcher.NO_MATCH);
matcher.addURI(AUTHORITY,"students",STUDENT_DIR);
matcher.addURI(AUTHORITY,"students/#",STUDENT_ITEM);
}
public boolean onCreate(){
helper=new MyOpenHelper(getContext());
return true;
}
public String getType(Uri uri){
switch(matcher.match(uri)){
case STUDENT_DIR:return "vnd.android.cursor.dir/vnd.com.jty.myapplication24.provider.student";
case STUDENT_ITEM:return "vnd.android.cursor.item/vnd.com.jty.myapplication24.provider.student";
}
return null;
}
public Uri insert(Uri uri, ContentValues values){
SQLiteDatabase db=helper.getReadableDatabase();
long id;
Uri renturn_uri=null;
switch (matcher.match(uri)){
case STUDENT_DIR: id=db.insert(uri.getPathSegments().get(0),"student_name",values);
renturn_uri=Uri.parse("content://"+AUTHORITY+"student"+id);break;
case STUDENT_ITEM: id=db.insert(uri.getPathSegments().get(0),"student_name",values);
renturn_uri=Uri.parse("content://"+AUTHORITY+"student"+id);break;
}
db.close();
return renturn_uri;
}
public int delete(Uri uri,String where,String[] selctionValue){
int num=0;
SQLiteDatabase db=helper.getReadableDatabase();
switch (matcher.match(uri)){
case STUDENT_DIR:num=db.delete(uri.getPathSegments().get(0),where,selctionValue);break;
case STUDENT_ITEM:num=db.delete(uri.getPathSegments().get(0),where,selctionValue);break;
}
return num;
}
public int update(Uri uri,ContentValues values,String where,String[] selctionValue){
int num=0;
SQLiteDatabase db=helper.getReadableDatabase();
switch (matcher.match(uri)){
case STUDENT_DIR:num=db.update(uri.getPathSegments().get(0),values,where,selctionValue);break;
case STUDENT_ITEM:num=db.update(uri.getPathSegments().get(0),values,where,selctionValue);break;
}
return num;
}
public Cursor query(Uri uri,String[] column,String where,String[] slectionValues,String orderBy){
Cursor cursor=null;
SQLiteDatabase db=helper.getReadableDatabase();
switch (matcher.match(uri)){
case STUDENT_DIR:cursor=db.query(uri.getPathSegments().get(0),column,where,slectionValues,null,null,orderBy);break;
case STUDENT_ITEM:cursor=db.query(uri.getPathSegments().get(0),column,where,slectionValues,null,null,orderBy);break;
}
return cursor;
}
}
注册代码
Activity代码
public class MainActivity extends AppCompatActivity {
ContentResolver resolver;
Uri uri;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
uri=Uri.parse("content://com.jty.myapplication24.provider/students");
resolver=getContentResolver();
}
public void click1(View v){
ContentValues values=new ContentValues();
values.put("student_name","jty");
values.put("student_age",18);
resolver.insert(uri,values);
}
public void click2(View v){
resolver.delete(uri,"student_age=?",new String[]{"18"});
}
public void click3(View v){
ContentValues values=new ContentValues();
values.put("student_name","zcf");
resolver.update(uri,values,"student_name=?",new String[]{"jty"});
}
public void click4(View v){
Cursor cursor=resolver.query(uri,null,null,null,null);
if(cursor!=null){
while(cursor.moveToNext()){
Log.i("id号:",cursor.getInt(cursor.getColumnIndex("student_id"))+"");
Log.i("姓名:",cursor.getString(cursor.getColumnIndex("student_name"))+"");
Log.i("年龄:",cursor.getInt(cursor.getColumnIndex("student_age"))+"");
}
}
}
}
运行结果
运行顺序:插入->查询->更改->查询->删除->查询