[转]Android共享数据ContentProvider的使用

本文转自:http://yaku2688.iteye.com/blog/1185364

 

ContentProvider数据共享

1.首先在AndroidManifest.xml文件中添加对外暴露的数据共享接口Content

Xml代码 复制代码 收藏代码
  1. <provider android:name=".UserProvider" android:authorities="com.yaku.ContentProvider.userprovider"/>  

 ContentProvider采用了authorities(主机名/域名)对它进行唯一标识,authorities 就是他的域名

 

2.Url解析
content://com.yaku.ContentProvider.userprovider/user/2
【content://】 Android定义的内容提供都的Schema
【com.yaku.ContentProvider.userprovider】  主机名或者authorities
【user】  路径
【2】 ID

 

示例代码:

数据结构User.java:

Java代码 复制代码 收藏代码
  1. package com.yaku.pojo;   
  2.   
  3. public class User {   
  4.     private int id;   
  5.     private String name;   
  6.     private int age;   
  7.        
  8.     public User(int id, String name, int age) {   
  9.         super();   
  10.         this.id = id;   
  11.         this.name = name;   
  12.         this.age = age;   
  13.     }   
  14.     public int getId() {   
  15.         return id;   
  16.     }   
  17.     public void setId(int id) {   
  18.         this.id = id;   
  19.     }   
  20.     public String getName() {   
  21.         return name;   
  22.     }   
  23.     public void setName(String name) {   
  24.         this.name = name;   
  25.     }   
  26.     public int getAge() {   
  27.         return age;   
  28.     }   
  29.     public void setAge(int age) {   
  30.         this.age = age;   
  31.     }   
  32.     @Override  
  33.     public String toString() {   
  34.         return "User [age=" + age + ", id=" + id + ", name=" + name + "]";   
  35.     }   
  36. }  

 

数据库操作DBOpenHelper.java:

Java代码 复制代码 收藏代码
  1. package com.yaku.db;   
  2.   
  3. import android.content.Context;   
  4. import android.database.sqlite.SQLiteDatabase;   
  5. import android.database.sqlite.SQLiteOpenHelper;   
  6.   
  7. public class DBOpenHelper extends SQLiteOpenHelper {   
  8.     private static final String DBNAME = "yaku.db"//数据库名称   
  9.     private static final int DBVER = 1;//数据库版本   
  10.        
  11.     public DBOpenHelper(Context context) {   
  12.         super(context, DBNAME, null, DBVER);   
  13.     }   
  14.   
  15.     @Override  
  16.     public void onCreate(SQLiteDatabase db) {   
  17.         String sql = "CREATE TABLE user (userid integer primary key autoincrement, name varchar(20), age integer)";   
  18.         db.execSQL(sql);//执行有更改的sql语句   
  19.     }   
  20.   
  21.     @Override  
  22.     public void onUpgrade(SQLiteDatabase db, int arg1, int arg2) {   
  23.         db.execSQL("DROP TABLE IF EXISTS user");   
  24.         onCreate(db);   
  25.     }   
  26.   
  27. }  

 

对外共享处理类ContentProviderUser.java:

Java代码 复制代码 收藏代码
  1. package com.yaku.ContentProvider;   
  2.   
  3. import com.yaku.db.DBOpenHelper;   
  4.   
  5. import android.content.ContentProvider;   
  6. import android.content.ContentUris;   
  7. import android.content.ContentValues;   
  8. import android.content.UriMatcher;   
  9. import android.database.Cursor;   
  10. import android.database.sqlite.SQLiteDatabase;   
  11. import android.net.Uri;   
  12.   
  13. public class ContentProviderUser extends ContentProvider {   
  14.     private DBOpenHelper dbOpenHelper;   
  15.     //常量UriMatcher.NO_MATCH表示不匹配任何路径的返回码   
  16.     private static final UriMatcher MATCHER = new UriMatcher(UriMatcher.NO_MATCH);   
  17.     private static final int USERS = 1;   
  18.     private static final int USER = 2;   
  19.     static{   
  20.         //如果match()方法匹配content://com.yaku.ContentProvider.userprovider/user路径,返回匹配码为1   
  21.         MATCHER.addURI("com.yaku.ContentProvider.userprovider""user", USERS);   
  22.         //如果match()方法匹配content://com.yaku.ContentProvider.userprovider/user/123路径,返回匹配码为2   
  23.         MATCHER.addURI("com.yaku.ContentProvider.userprovider""user/#", USER);//#号为通配符   
  24.     }      
  25.     @Override  
  26.     public int delete(Uri uri, String selection, String[] selectionArgs) {   
  27.         SQLiteDatabase db = dbOpenHelper.getWritableDatabase();   
  28.         int count = 0;   
  29.         switch (MATCHER.match(uri)) {   
  30.         case USERS:   
  31.             count = db.delete("user", selection, selectionArgs);   
  32.             return count;   
  33.         case USER:   
  34.             //ContentUris类用于获取Uri路径后面的ID部分   
  35.             long id = ContentUris.parseId(uri);   
  36.             String where = "userid = "+ id;   
  37.             if(selection!=null && !"".equals(selection)){   
  38.                 where = selection + " and " + where;   
  39.             }   
  40.             count = db.delete("user", where, selectionArgs);   
  41.             return count;   
  42.         default:   
  43.             throw new IllegalArgumentException("Unkwon Uri:"+ uri.toString());   
  44.         }   
  45.     }   
  46.   
  47.     /**  
  48.      * 该方法用于返回当前Url所代表数据的MIME类型。  
  49.      * 如果操作的数据属于集合类型,那么MIME类型字符串应该以vnd.android.cursor.dir/开头  
  50.      * 如果要操作的数据属于非集合类型数据,那么MIME类型字符串应该以vnd.android.cursor.item/开头  
  51.      */  
  52.     @Override  
  53.     public String getType(Uri uri) {   
  54.         switch (MATCHER.match(uri)) {   
  55.         case USERS:            
  56.             return "vnd.android.cursor.dir/user";   
  57.                
  58.         case USER:             
  59.             return "vnd.android.cursor.item/user";   
  60.                
  61.         default:   
  62.             throw new IllegalArgumentException("Unkwon Uri:"+ uri.toString());   
  63.         }   
  64.     }   
  65.   
  66.     @Override  
  67.     public Uri insert(Uri uri, ContentValues values) {   
  68.         SQLiteDatabase db = dbOpenHelper.getWritableDatabase();   
  69.         switch (MATCHER.match(uri)) {   
  70.         case USERS:   
  71.             long rowid = db.insert("user""name", values);    
  72.             Uri insertUri = ContentUris.withAppendedId(uri, rowid);//得到代表新增记录的Uri   
  73.             this.getContext().getContentResolver().notifyChange(uri, null);   
  74.             return insertUri;   
  75.   
  76.         default:   
  77.             throw new IllegalArgumentException("Unkwon Uri:"+ uri.toString());   
  78.         }   
  79.     }   
  80.   
  81.     @Override  
  82.     public boolean onCreate() {   
  83.         this.dbOpenHelper = new DBOpenHelper(this.getContext());   
  84.         return false;   
  85.     }   
  86.   
  87.     @Override  
  88.     public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,   
  89.             String sortOrder) {   
  90.         SQLiteDatabase db = dbOpenHelper.getReadableDatabase();   
  91.         switch (MATCHER.match(uri)) {   
  92.         case USERS:   
  93.             return db.query("user", projection, selection, selectionArgs, nullnull, sortOrder);   
  94.         case USER:   
  95.             long id = ContentUris.parseId(uri);   
  96.             String where = "userid = "+ id;   
  97.             if(selection!=null && !"".equals(selection)){   
  98.                 where = selection + " and " + where;   
  99.             }   
  100.             return db.query("user", projection, where, selectionArgs, nullnull, sortOrder);   
  101.         default:   
  102.             throw new IllegalArgumentException("Unkwon Uri:"+ uri.toString());   
  103.         }   
  104.     }   
  105.   
  106.     @Override  
  107.     public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {   
  108.         SQLiteDatabase db = dbOpenHelper.getWritableDatabase();   
  109.         int count = 0;   
  110.         switch (MATCHER.match(uri)) {   
  111.         case USERS:   
  112.             count = db.update("person", values, selection, selectionArgs);   
  113.             return count;   
  114.         case USER:   
  115.             long id = ContentUris.parseId(uri);   
  116.             String where = "userid = "+ id;   
  117.             if(selection!=null && !"".equals(selection)){   
  118.                 where = selection + " and " + where;   
  119.             }   
  120.             count = db.update("user", values, where, selectionArgs);   
  121.             return count;   
  122.         default:   
  123.             throw new IllegalArgumentException("Unkwon Uri:"+ uri.toString());   
  124.         }   
  125.     }   
  126. }  

 

单元测试类(在另一个应用中):

 

 

Java代码 复制代码 收藏代码
  1. package com.yaku.ContentProvider;   
  2.   
  3. import android.content.ContentResolver;   
  4. import android.content.ContentValues;   
  5. import android.database.Cursor;   
  6. import android.net.Uri;   
  7. import android.test.AndroidTestCase;   
  8. import android.util.Log;   
  9.   
  10. /**  
  11.  * 对ContentProvider工程中的ContentProviderActivity进行单元测试  
  12.  */  
  13. public class ContentProviderActivityTest extends AndroidTestCase {   
  14.     private static final String TAG = "ContentProvider";   
  15.     //往内容提供者添加数据   
  16.     public void testInsert() throws Throwable{   
  17.         ContentResolver contentResolver = this.getContext().getContentResolver();   
  18.         Uri insertUri = Uri.parse("content://com.yaku.ContentProvider.userprovider/user");   
  19.         ContentValues values = new ContentValues();   
  20.         values.put("name""道长");   
  21.         values.put("age"86);   
  22.         Uri uri = contentResolver.insert(insertUri, values);   
  23.         Log.i(TAG, uri.toString());   
  24.     }   
  25.        
  26.     //更新内容提供者中的数据   
  27.     public void testUpdate() throws Throwable{   
  28.         ContentResolver contentResolver = this.getContext().getContentResolver();   
  29.         Uri updateUri = Uri.parse("content://com.yaku.ContentProvider.userprovider/user/1");   
  30.         ContentValues values = new ContentValues();   
  31.         values.put("name""青眉道长");   
  32.         contentResolver.update(updateUri, values, nullnull);   
  33.     }   
  34.        
  35.     //从内容提供者中删除数据   
  36.     public void testDelete() throws Throwable{   
  37.         ContentResolver contentResolver = this.getContext().getContentResolver();   
  38.         Uri deleteUri = Uri.parse("content://com.yaku.ContentProvider.userprovider/user/1");   
  39.         contentResolver.delete(deleteUri, nullnull);   
  40.     }   
  41.        
  42.     //获取内容提供者中的数据   
  43.     public void testFind() throws Throwable{   
  44.         ContentResolver contentResolver = this.getContext().getContentResolver();   
  45.         Uri selectUri = Uri.parse("content://com.yaku.ContentProvider.userprovider/user");   
  46.         Cursor cursor = contentResolver.query(selectUri, nullnullnull"userid desc");   
  47.         while(cursor.moveToNext()){   
  48.             int id = cursor.getInt(cursor.getColumnIndex("userid"));   
  49.             String name = cursor.getString(cursor.getColumnIndex("name"));   
  50.             int age = cursor.getInt(cursor.getColumnIndex("age"));   
  51.             Log.i(TAG, "id="+ id + ",name="+ name+ ",age="+ age);   
  52.         }   
  53.     }   
  54.        
  55. }  

 

监听数据的变化:

Java代码 复制代码 收藏代码
  1. <SPAN style="FONT-SIZE: medium">package com.yaku.ContentProvider;   
  2.   
  3. import android.content.ContentResolver;   
  4. import android.content.ContentValues;   
  5. import android.database.Cursor;   
  6. import android.net.Uri;   
  7. import android.test.AndroidTestCase;   
  8. import android.util.Log;   
  9.   
  10. /**  
  11.  * 监听数据变化  
  12.  */  
  13. public class OtherContentProviderTest extends AndroidTestCase {   
  14.     private static final String TAG = "OtherContentProvider";   
  15.        
  16.     @Override  
  17.     public void onCreate(Bundle savedInstanceState) {   
  18.         super.onCreate(savedInstanceState);   
  19.         setContentView(R.layout.main);   
  20.            
  21.         Uri insertUri = Uri.parse("content://com.yaku.ContentProvider.userprovider/user");   
  22.         ContentResolver contentResolver = this.getContentResolver();   
  23.         //对指定uri进行监听,如果该uri代表的数据发生变化,就会调用PersonObserver中的onChange()   
  24.         contentResolver.registerContentObserver(insertUri, truenew PersonObserver(new Handler()));   
  25.     }   
  26.        
  27.     private final class PersonObserver extends ContentObserver{   
  28.         public PersonObserver(Handler handler) {   
  29.             super(handler);   
  30.         }   
  31.   
  32.         @Override  
  33.         public void onChange(boolean selfChange) {   
  34.             ContentResolver contentResolver = getContentResolver();   
  35.             Uri selectUri = Uri.parse("content://com.yaku.ContentProvider.userprovider/user");   
  36.             Cursor cursor = contentResolver.query(selectUri, nullnullnull"userid desc");   
  37.             while(cursor.moveToNext()){   
  38.                 int id = cursor.getInt(cursor.getColumnIndex("userid"));   
  39.                 String name = cursor.getString(cursor.getColumnIndex("name"));   
  40.                 int age = cursor.getInt(cursor.getColumnIndex("age"));   
  41.                 Log.i(TAG, "id="+ id + ",name="+ name+ ",age="+ age);   
  42.             }   
  43.         }   
  44.     }   
  45. }   
  46. </SPAN>  

 

 

posted on 2011-12-30 10:54  freeliver54  阅读(2206)  评论(4编辑  收藏  举报

导航