Android_ContentProvider详解(实现增删改查)

来源:互联网 发布:unity3d教程百度云 编辑:程序博客网 时间:2024/06/06 01:22
 

Android_ContentProvider详解(实现增删改查)

标签: UriMatcherUri内容提供者ContentProviderAndroid
 943人阅读 评论(0) 收藏 举报
本文章已收录于: 
 Android知识库
 分类:

目录(?)[+]

1.概述

ContentProvider为存储和读取数据提供了统一的接口,实现了程序间的数据共享,而应用程序内部没有必要实现这个功能,直接操作数据库就可以!Android内置的许多数据都是使用ContentProvider形式,供开发者调用的(如视频,音频,图片,通讯录等)。
当应用继承ContentProvider类,并重写该类用于提供数据和存储数据的方法,就可以向其他应用共享其数据,统一了数据访问方式。

2.提供一个ContentProvider

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. /* 
  2.  * PersonProvider.java 
  3.  * 内容提供者 
  4.  */  
  5. public class PersonProvider extends ContentProvider {  
  6.     private SQLiteDatabase db;      //需要操作的数据库  
  7.     private final static int PERSON = 1;  
  8.     private final static int PERSONID = 2;  
  9.     private final static int DELPERSONID = 3;  
  10.     private final static int PERSONS = 4;  
  11.     //  1.定义一个静态常量字段Uri匹配器,用以匹配uri  
  12.     private final static UriMatcher MATCHER = new UriMatcher(UriMatcher.NO_MATCH);  //如果都匹配不成功,则返回构造函数中指定的参数值,默认为-1  
  13.     //  2.静态代码块  
  14.     static{  
  15.         /* 
  16.          * Add a URI to match, and the code to return when this URI is matched.  
  17.          * 使用"*"去匹配任意的文本数据,或者使用"#"去匹配任意的数字 
  18.          * MATCHER.addURI(String authority,     //  主机名或者认证 com.baidu.provider.person 
  19.          *                  String path,        //  路径 authority/path 
  20.          *                  int code)           //  与这个authority的path路径想对应的,一个int的数字,使用MATCHER.match(uri) 返回code数字 
  21.          */  
  22.         MATCHER.addURI("com.baidu.provider.person""person", PERSON);  //  
  23.         MATCHER.addURI("com.baidu.provider.person""persons", PERSONS);  
  24.         MATCHER.addURI("com.baidu.provider.person""person/update/#", PERSONID);  
  25.         MATCHER.addURI("com.baidu.provider.person""person/delete/#", DELPERSONID);  
  26.     }  
  27.     //  3.onCreate方法完成provider的初始化动作,主要是数据库的构建  
  28.     @Override  
  29.     public boolean onCreate() {  
  30.         DbOpenHelper dbOpenHelper = new DbOpenHelper(this.getContext());  
  31.         db = dbOpenHelper.getWritableDatabase();  
  32.         return true;  
  33.     }  
  34.       
  35.     /* 
  36.      *  4.覆写需要的方法 
  37.      *      query,insert,delete,update 
  38.      */  
  39.     @Override  
  40.     public Uri insert(Uri uri, ContentValues values) {  
  41.         //4.1 使用uri匹配器去匹配一个uri,根据int返回值来判断具体的操作类型  
  42.         switch (MATCHER.match(uri)) {     
  43.         case PERSON:  
  44.         //4.2与uri想匹配的响应操作  
  45.             long id = db.insert("person""name", values);  //返回id  
  46.             uri = ContentUris.withAppendedId(uri, id);      //返回需求的uri  
  47.             break;  
  48.         default:  
  49.             break;  
  50.         }  
  51.         return uri;  
  52.     }  
  53. }  
[html] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. <!-- AndroidManifest.xml -->  
  2. <provider android:name=".PersonProvider" android:authorities="com.baidu.provider.person"></provider>  

3.ContentProvider的增删改查

(1).增加操作

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. /* 
  2.  *  ContentProvider 增操作 
  3.  */  
  4. // 提供者内部方法  
  5. public Uri insert(Uri uri, ContentValues values) {  
  6.     switch (MATCHER.match(uri)) {  
  7.     case PERSON:  
  8.         long id = db.insert("person""name", values);  
  9.         uri = ContentUris.withAppendedId(uri, id);      //注意使用这个简便的操作方法,来生成一个uri  
  10.         break;  
  11.     default:  
  12.         break;  
  13.     }  
  14.     return uri;  
  15. }  
  16. // 使用提供者的内部方法  
  17. public void insertMethod(){  
  18.     ContentResolver resolver = MainActivity.this.getApplicationContext().getContentResolver();  
  19.     Uri uri = Uri.parse("content://com.baidu.provider.person/person");  
  20.     List<String> list = uri.getPathSegments();  
  21.     ContentValues values = new ContentValues();  
  22.     values.put("name""zhang");  
  23.     values.put("age""20");  
  24.     Uri resultUri = resolver.insert(uri, values);  
  25.     if(ContentUris.parseId(resultUri) > 0){      //根据uri,解析出其中的id值  
  26.         show("插入成功!");  
  27.     }else{  
  28.         show("插入失败!");  
  29.     }  
  30. }  
  31. public void show(String info){  
  32.     Toast.makeText(this, info, Toast.LENGTH_SHORT).show();  
  33. }  

(2).删除操作

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. /* 
  2.  *  ContentProvider 删操作 
  3.  */  
  4. // 提供者内部方法  
  5. public int delete(Uri uri, String selection, String[] selectionArgs) {  
  6.     int resultId = 0;  
  7.     switch (MATCHER.match(uri)) {  
  8.     case DELPERSONID:  
  9.         long id = ContentUris.parseId(uri);     //根据uri对象,解析出其中的id,解析失败返回为-1  
  10.         if(selection != null){  
  11.             selection += (" and _id="+id);  
  12.         }else{  
  13.             selection = ("_id="+id);  
  14.         }  
  15.         resultId = db.delete("person", selection, selectionArgs);   //返回删除成功的行号值  
  16.         break;  
  17.     }  
  18.     return resultId;  
  19. }  
  20. //使用提供者的内部方法  
  21. public void deleteMethod(){  
  22.     ContentResolver resolver = MainActivity.this.getApplicationContext().getContentResolver();  
  23.     Uri uri = Uri.parse("content://com.baidu.provider.person/person/delete/6");  
  24.     int id = resolver.delete(uri, nullnull);  
  25.     if(id > 0){  
  26.         show("删除成功!");  
  27.     }else{  
  28.         show("删除失败!");  
  29.     }  
  30. }  
  31. public void show(String info){  
  32.     Toast.makeText(this, info, Toast.LENGTH_SHORT).show();  
  33. }  

(3).更新操作

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. /* 
  2.  *  ContentProvider 更新操作 
  3.  */  
  4. // 提供者内部方法  
  5. public int update(Uri uri, ContentValues values, String selection,  
  6.         String[] selectionArgs) {  
  7.     int resultId = 0;  
  8.     switch (MATCHER.match(uri)) {  
  9.     case PERSONID:  
  10.         long id = ContentUris.parseId(uri);  
  11.         if(selection != null){  
  12.             selection += (" and _id="+id);  
  13.         }else{  
  14.             selection = ("_id="+id);  
  15.         }  
  16.         resultId = db.update("person", values, selection, selectionArgs);  
  17.         break;  
  18.     default:  
  19.         break;  
  20.     }  
  21.     return resultId;  
  22. }  
  23. //使用提供者的内部方法  
  24. public void updateMethod(){  
  25.     ContentResolver resolver = MainActivity.this.getApplicationContext().getContentResolver();  
  26.     Uri uri = Uri.parse("content://com.baidu.provider.person/person/update/5");  
  27.     ContentValues values = new ContentValues();  
  28.     values.put("name""li");  
  29.     values.put("age""24");  
  30.     int id = resolver.update(uri, values, nullnull);  
  31.     if(id > 0){  
  32.         show("更新成功!");  
  33.     }else{  
  34.         show("更新失败!");  
  35.     }  
  36. }  
  37. public void show(String info){  
  38.     Toast.makeText(this, info, Toast.LENGTH_SHORT).show();  
  39. }  

(4).查询操作

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. /* 
  2.  *  ContentProvider 查询操作 
  3.  */  
  4. // 提供者内部方法  
  5. public Cursor query(Uri uri, String[] projection, String selection,  
  6.         String[] selectionArgs, String sortOrder) {  
  7.     Cursor cursor = null;  
  8.     switch (MATCHER.match(uri)) {  
  9.     case PERSONS:  
  10.         cursor = db.query("person", projection, selection, selectionArgs, nullnull, sortOrder);  
  11.         break;  
  12.     default:  
  13.         break;  
  14.     }  
  15.     return cursor;  
  16. }  
  17. //使用提供者的内部方法  
  18. ContentResolver resolver = MainActivity.this.getApplicationContext().getContentResolver();  
  19. Uri uri = Uri.parse("content://com.baidu.provider.persons");  
  20. Cursor cursor = resolver.query(uri, nullnullnullnull);  
  21. if(cursor != null){  
  22.     list.setAdapter(new SimpleCursorAdapter(MainActivity.this, R.layout.item, cursor, new String[]{"_id""name""age"}, new int[]{R.id.id, R.id.name, R.id.age}));  
  23.     show("查询成功!");  
  24. }else{  
  25.     show("查询失败!");  
  26. }  
  27. public void show(String info){  
  28.     Toast.makeText(this, info, Toast.LENGTH_SHORT).show();  
  29. }  

4.内容观察者

在listView中,使用内容提供者动态更新数据
[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. ContentResolver resolver = getContentResolver();  
  2. Uri uri = Uri.parse("content://sms/");  
  3. resolver.registerContentObserver(uri, truenew ContentObserver(new Handler()) {  
  4.     @Override  
  5.     public void onChange(boolean selfChange) {  
  6.         super.onChange(selfChange);  
  7.         /* 
  8.          * 发送一个Message对象 
  9.          * 有handler对对象进行处理 
  10.          */  
  11.     }  
  12. });  

5.操作示意图

                

0 0