[转]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. }  

    package com.yaku.pojo;

    public class User {

    private int id;
    private String name;
    private int age;
    
    public User(int id, String name, int age) {
        super();
        this.id = id;
        this.name = name;
        this.age = age;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    @Override
    public String toString() {
        return "User [age=" + age + ", id=" + id + ", name=" + name + "]";
    }
    

    }

 

数据库操作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. }  

    package com.yaku.db;

    import android.content.Context;
    import android.database.sqlite.SQLiteDatabase;
    import android.database.sqlite.SQLiteOpenHelper;

    public class DBOpenHelper extends SQLiteOpenHelper {

    private static final String DBNAME = "yaku.db"; //数据库名称
    private static final int DBVER = 1;//数据库版本
    
    public DBOpenHelper(Context context) {
        super(context, DBNAME, null, DBVER);
    }
    
    @Override
    public void onCreate(SQLiteDatabase db) {
        String sql = "CREATE TABLE user (userid integer primary key autoincrement, name varchar(20), age integer)";
        db.execSQL(sql);//执行有更改的sql语句
    }
    
    @Override
    public void onUpgrade(SQLiteDatabase db, int arg1, int arg2) {
        db.execSQL("DROP TABLE IF EXISTS user");
        onCreate(db);
    }
    

    }

 

对外共享处理类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, null, null, 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, null, null, 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. }  

    package com.yaku.ContentProvider;

    import com.yaku.db.DBOpenHelper;

    import android.content.ContentProvider;
    import android.content.ContentUris;
    import android.content.ContentValues;
    import android.content.UriMatcher;
    import android.database.Cursor;
    import android.database.sqlite.SQLiteDatabase;
    import android.net.Uri;

    public class ContentProviderUser extends ContentProvider {
    private DBOpenHelper dbOpenHelper;
    //常量UriMatcher.NO_MATCH表示未兼容任何路径的返回码
    private static final UriMatcher MATCHER = new UriMatcher(UriMatcher.NO_MATCH);
    private static final int USERS = 1;
    private static final int USER = 2;
    static{

       //如果match()方法匹配content://com.yaku.ContentProvider.userprovider/user路径,返回匹配码为1
       MATCHER.addURI("com.yaku.ContentProvider.userprovider", "user", USERS);
       //如果match()方法匹配content://com.yaku.ContentProvider.userprovider/user/123路径,返回匹配码为2
       MATCHER.addURI("com.yaku.ContentProvider.userprovider", "user/#", USER);//#号为通配符
    

    }
    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {

       SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
       int count = 0;
       switch (MATCHER.match(uri)) {
       case USERS:
           count = db.delete("user", selection, selectionArgs);
           return count;
       case USER:
           //ContentUris类用于获取Uri路径后面的ID部分
           long id = ContentUris.parseId(uri);
           String where = "userid = "+ id;
           if(selection!=null && !"".equals(selection)){
               where = selection + " and " + where;
           }
           count = db.delete("user", where, selectionArgs);
           return count;
       default:
           throw new IllegalArgumentException("Unkwon Uri:"+ uri.toString());
       }
    

    }

    /**

    * 该方法用于返回当前Url所代表数据的MIME类型。
    * 如果操作的数据属于集合类型,那么MIME类型字符串应该以vnd.android.cursor.dir/开头
    * 如果要操作的数据属于非集合类型数据,那么MIME类型字符串应该以vnd.android.cursor.item/开头
    */
    

    @Override
    public String getType(Uri uri) {

       switch (MATCHER.match(uri)) {
       case USERS:         
           return "vnd.android.cursor.dir/user";
    
       case USER:          
           return "vnd.android.cursor.item/user";
    
       default:
           throw new IllegalArgumentException("Unkwon Uri:"+ uri.toString());
       }
    

    }

    @Override
    public Uri insert(Uri uri, ContentValues values) {

       SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
       switch (MATCHER.match(uri)) {
       case USERS:
           long rowid = db.insert("user", "name", values); 
           Uri insertUri = ContentUris.withAppendedId(uri, rowid);//得到代表新增记录的Uri
           this.getContext().getContentResolver().notifyChange(uri, null);
           return insertUri;
    
       default:
           throw new IllegalArgumentException("Unkwon Uri:"+ uri.toString());
       }
    

    }

    @Override
    public boolean onCreate() {

       this.dbOpenHelper = new DBOpenHelper(this.getContext());
       return false;
    

    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,

           String sortOrder) {
       SQLiteDatabase db = dbOpenHelper.getReadableDatabase();
       switch (MATCHER.match(uri)) {
       case USERS:
           return db.query("user", projection, selection, selectionArgs, null, null, sortOrder);
       case USER:
           long id = ContentUris.parseId(uri);
           String where = "userid = "+ id;
           if(selection!=null && !"".equals(selection)){
               where = selection + " and " + where;
           }
           return db.query("user", projection, where, selectionArgs, null, null, sortOrder);
       default:
           throw new IllegalArgumentException("Unkwon Uri:"+ uri.toString());
       }
    

    }

    @Override
    public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {

       SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
       int count = 0;
       switch (MATCHER.match(uri)) {
       case USERS:
           count = db.update("person", values, selection, selectionArgs);
           return count;
       case USER:
           long id = ContentUris.parseId(uri);
           String where = "userid = "+ id;
           if(selection!=null && !"".equals(selection)){
               where = selection + " and " + where;
           }
           count = db.update("user", values, where, selectionArgs);
           return count;
       default:
           throw new IllegalArgumentException("Unkwon Uri:"+ uri.toString());
       }
    

    }
    }

 

单元测试类(在其余一个用到被):

 

 

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, null, null);   
  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, null, null);   
  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, null, null, null, “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. }  

    package com.yaku.ContentProvider;

    import android.content.ContentResolver;
    import android.content.ContentValues;
    import android.database.Cursor;
    import android.net.Uri;
    import android.test.AndroidTestCase;
    import android.util.Log;

    /**

    • 针对ContentProvider工程中的ContentProviderActivity进行单元测试
      */
      public class ContentProviderActivityTest extends AndroidTestCase {
      private static final String TAG = “ContentProvider”;
      //往内容提供者添加数据
      public void testInsert() throws Throwable{

       ContentResolver contentResolver = this.getContext().getContentResolver();
       Uri insertUri = Uri.parse("content://com.yaku.ContentProvider.userprovider/user");
       ContentValues values = new ContentValues();
       values.put("name", "道长");
       values.put("age", 86);
       Uri uri = contentResolver.insert(insertUri, values);
       Log.i(TAG, uri.toString());
      

      }

      //更新内容提供者中之多少
      public void testUpdate() throws Throwable{

       ContentResolver contentResolver = this.getContext().getContentResolver();
       Uri updateUri = Uri.parse("content://com.yaku.ContentProvider.userprovider/user/1");
       ContentValues values = new ContentValues();
       values.put("name", "青眉道长");
       contentResolver.update(updateUri, values, null, null);
      

      }

      //从内容提供者中删去数据
      public void testDelete() throws Throwable{

       ContentResolver contentResolver = this.getContext().getContentResolver();
       Uri deleteUri = Uri.parse("content://com.yaku.ContentProvider.userprovider/user/1");
       contentResolver.delete(deleteUri, null, null);
      

      }

      //获取内容提供者中之数
      public void testFind() throws Throwable{

       ContentResolver contentResolver = this.getContext().getContentResolver();
       Uri selectUri = Uri.parse("content://com.yaku.ContentProvider.userprovider/user");
       Cursor cursor = contentResolver.query(selectUri, null, null, null, "userid desc");
       while(cursor.moveToNext()){
           int id = cursor.getInt(cursor.getColumnIndex("userid"));
           String name = cursor.getString(cursor.getColumnIndex("name"));
           int age = cursor.getInt(cursor.getColumnIndex("age"));
           Log.i(TAG, "id="+ id + ",name="+ name+ ",age="+ age);
       }
      

      }

    }

 

监听数据的转:

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, true, new 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, null, null, null, “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>  

    package com.yaku.ContentProvider;

    import android.content.ContentResolver;
    import android.content.ContentValues;
    import android.database.Cursor;
    import android.net.Uri;
    import android.test.AndroidTestCase;
    import android.util.Log;

    /**

    • 监听数据变化
      */
      public class OtherContentProviderTest extends AndroidTestCase {
      private static final String TAG = “OtherContentProvider”;

      @Override
      public void onCreate(Bundle savedInstanceState) {

       super.onCreate(savedInstanceState);
       setContentView(R.layout.main);
      
       Uri insertUri = Uri.parse("content://com.yaku.ContentProvider.userprovider/user");
       ContentResolver contentResolver = this.getContentResolver();
       //对指定uri进行监听,如果该uri代表的数据发生变化,就会调用PersonObserver中的onChange()
       contentResolver.registerContentObserver(insertUri, true, new PersonObserver(new Handler()));
      

      }

      private final class PersonObserver extends ContentObserver{

       public PersonObserver(Handler handler) {
           super(handler);
       }
      
       @Override
       public void onChange(boolean selfChange) {
           ContentResolver contentResolver = getContentResolver();
           Uri selectUri = Uri.parse("content://com.yaku.ContentProvider.userprovider/user");
           Cursor cursor = contentResolver.query(selectUri, null, null, null, "userid desc");
           while(cursor.moveToNext()){
               int id = cursor.getInt(cursor.getColumnIndex("userid"));
               String name = cursor.getString(cursor.getColumnIndex("name"));
               int age = cursor.getInt(cursor.getColumnIndex("age"));
               Log.i(TAG, "id="+ id + ",name="+ name+ ",age="+ age);
           }
       }
      

      }
      }

 

 

网站地图xml地图