[轉]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>  

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM