1、ContentProvider簡介
當應用繼承ContentProvider類,並重寫該類用於提供數據和存儲數據的方法,就能夠向其餘應用共享其數據。雖然使用其餘方法也能夠對外共享數據,但數據訪問方式會因數據存儲的方式而不一樣,如:採用文件方式對外共享數據,須要進行文件操做讀寫數據;採用sharedpreferences共享數據,須要使用sharedpreferences API讀寫數據。而使用ContentProvider共享數據的好處是統一了數據訪問方式。
2、Uri類簡介
Uri表明了要操做的數據,Uri主要包含了兩部分信息:1.須要操做的ContentProvider ,2.對ContentProvider中的什麼數據進行操做,一個Uri由如下幾部分組成:
1.scheme:ContentProvider(內容提供者)的scheme已經由Android所規定爲:content://。
2.主機名(或Authority):用於惟一標識這個ContentProvider,外部調用者能夠根據這個標識來找到它。
3.路徑(path):能夠用來表示咱們要操做的數據,路徑的構建應根據業務而定,以下:
• 要操做contact表中id爲10的記錄,能夠構建這樣的路徑:/contact/10
• 要操做contact表中id爲10的記錄的name字段, contact/10/name
• 要操做contact表中的全部記錄,能夠構建這樣的路徑:/contact
要操做的數據不必定來自數據庫,也能夠是文件等他存儲方式,以下:
要操做xml文件中contact節點下的name節點,能夠構建這樣的路徑:/contact/name
若是要把一個字符串轉換成Uri,可使用Uri類中的parse()方法,以下:
Uri uri = Uri.parse("content://com.changcheng.provider.contactprovider/contact")
3、UriMatcher、ContentUrist和ContentResolver簡介
由於Uri表明了要操做的數據,因此咱們很常常須要解析Uri,並從Uri中獲取數據。Android系統提供了兩個用於操做Uri的工具類,分別爲UriMatcher 和ContentUris 。掌握它們的使用,會便於咱們的開發工做。
UriMatcher:用於匹配Uri,它的用法以下:
1.首先把你須要匹配Uri路徑所有給註冊上,以下:
//常量UriMatcher.NO_MATCH表示不匹配任何路徑的返回碼(-1)。
UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
//若是match()方法匹配content://com.changcheng.sqlite.provider.contactprovider/contact路徑,返回匹配碼爲1
uriMatcher.addURI(「com.changcheng.sqlite.provider.contactprovider」, 「contact」, 1);//添加須要匹配uri,若是匹配就會返回匹配碼
//若是match()方法匹配 content://com.changcheng.sqlite.provider.contactprovider/contact/230路徑,返回匹配碼爲2
uriMatcher.addURI(「com.changcheng.sqlite.provider.contactprovider」, 「contact/#」, 2);//#號爲通配符
2.註冊完須要匹配的Uri後,就可使用uriMatcher.match(uri)方法對輸入的Uri進行匹配,若是匹配就返回匹配碼,匹配碼是調用addURI()方法傳入的第三個參數,假設匹配content://com.changcheng.sqlite.provider.contactprovider/contact路徑,返回的匹配碼爲1。
ContentUris:用於獲取Uri路徑後面的ID部分,它有兩個比較實用的方法:
• withAppendedId(uri, id)用於爲路徑加上ID部分
• parseId(uri)方法用於從路徑中獲取ID部分
ContentResolver:當外部應用須要對ContentProvider中的數據進行添加、刪除、修改和查詢操做時,可使用ContentResolver 類來完成,要獲取ContentResolver 對象,可使用Activity提供的getContentResolver()方法。 ContentResolver使用insert、delete、update、query方法,來操做數據。
4、ContentProvider示例程序
Manifest.xml中的代碼:java
<application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".TestWebviewDemo" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> <intent-filter> <data android:mimeType="vnd.android.cursor.dir/vnd.ruixin.login" /> </intent-filter> <intent-filter> <data android:mimeType="vnd.android.cursor.item/vnd.ruixin.login" /> </intent-filter> </activity> <provider android:name="MyProvider" android:authorities="com.ruixin.login" /> </application>
須要在<application></application>中爲provider進行註冊!!!!
首先定義一個數據庫的工具類:android
public class RuiXin { public static final String DBNAME = "ruixinonlinedb"; public static final String TNAME = "ruixinonline"; public static final int VERSION = 3; public static String TID = "tid"; public static final String EMAIL = "email"; public static final String USERNAME = "username"; public static final String DATE = "date"; public static final String SEX = "sex"; public static final String AUTOHORITY = "com.ruixin.login"; public static final int ITEM = 1; public static final int ITEM_ID = 2; public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.ruixin.login"; public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.ruixin.login"; public static final Uri CONTENT_URI = Uri.parse("content://" + AUTOHORITY + "/ruixinonline"); }
而後建立一個數據庫:sql
public class DBlite extends SQLiteOpenHelper { public DBlite(Context context) { super(context, RuiXin.DBNAME, null, RuiXin.VERSION); // TODO Auto-generated constructor stub } @Override public void onCreate(SQLiteDatabase db) { // TODO Auto-generated method stub db.execSQL("create table "+RuiXin.TNAME+"(" + RuiXin.TID+" integer primary key autoincrement not null,"+ RuiXin.EMAIL+" text not null," + RuiXin.USERNAME+" text not null," + RuiXin.DATE+" interger not null,"+ RuiXin.SEX+" text not null);"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // TODO Auto-generated method stub } public void add(String email,String username,String date,String sex){ SQLiteDatabase db = getWritableDatabase(); ContentValues values = new ContentValues(); values.put(RuiXin.EMAIL, email); values.put(RuiXin.USERNAME, username); values.put(RuiXin.DATE, date); values.put(RuiXin.SEX, sex); db.insert(RuiXin.TNAME,"",values); } }
接着建立一個Myprovider.java對數據庫的接口進行包裝:數據庫
public class MyProvider extends ContentProvider{ DBlite dBlite; SQLiteDatabase db; private static final UriMatcher sMatcher; static{ sMatcher = new UriMatcher(UriMatcher.NO_MATCH); sMatcher.addURI(RuiXin.AUTOHORITY,RuiXin.TNAME, RuiXin.ITEM); sMatcher.addURI(RuiXin.AUTOHORITY, RuiXin.TNAME+"/#", RuiXin.ITEM_ID); } @Override public int delete(Uri uri, String selection, String[] selectionArgs) { // TODO Auto-generated method stub db = dBlite.getWritableDatabase(); int count = 0; switch (sMatcher.match(uri)) { case RuiXin.ITEM: count = db.delete(RuiXin.TNAME,selection, selectionArgs); break; case RuiXin.ITEM_ID: String id = uri.getPathSegments().get(1); count = db.delete(RuiXin.TID, RuiXin.TID+"="+id+(!TextUtils.isEmpty(RuiXin.TID="?")?"AND("+selection+')':""), selectionArgs); break; default: throw new IllegalArgumentException("Unknown URI"+uri); } getContext().getContentResolver().notifyChange(uri, null); return count; } @Override public String getType(Uri uri) { // TODO Auto-generated method stub switch (sMatcher.match(uri)) { case RuiXin.ITEM: return RuiXin.CONTENT_TYPE; case RuiXin.ITEM_ID: return RuiXin.CONTENT_ITEM_TYPE; default: throw new IllegalArgumentException("Unknown URI"+uri); } } @Override public Uri insert(Uri uri, ContentValues values) { // TODO Auto-generated method stub db = dBlite.getWritableDatabase(); long rowId; if(sMatcher.match(uri)!=RuiXin.ITEM){ throw new IllegalArgumentException("Unknown URI"+uri); } rowId = db.insert(RuiXin.TNAME,RuiXin.TID,values); if(rowId>0){ Uri noteUri=ContentUris.withAppendedId(RuiXin.CONTENT_URI, rowId); getContext().getContentResolver().notifyChange(noteUri, null); return noteUri; } throw new IllegalArgumentException("Unknown URI"+uri); } @Override public boolean onCreate() { // TODO Auto-generated method stub this.dBlite = new DBlite(this.getContext()); // db = dBlite.getWritableDatabase(); // return (db == null)?false:true; return true; } @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { // TODO Auto-generated method stub db = dBlite.getWritableDatabase(); Cursor c; Log.d("-------", String.valueOf(sMatcher.match(uri))); switch (sMatcher.match(uri)) { case RuiXin.ITEM: c = db.query(RuiXin.TNAME, projection, selection, selectionArgs, null, null, null); break; case RuiXin.ITEM_ID: String id = uri.getPathSegments().get(1); c = db.query(RuiXin.TNAME, projection, RuiXin.TID+"="+id+(!TextUtils.isEmpty(selection)?"AND("+selection+')':""),selectionArgs, null, null, sortOrder); break; default: Log.d("!!!!!!", "Unknown URI"+uri); throw new IllegalArgumentException("Unknown URI"+uri); } c.setNotificationUri(getContext().getContentResolver(), uri); return c; } @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { // TODO Auto-generated method stub return 0; } }
最後建立測試類:app
public class Test extends Activity { /** Called when the activity is first created. */ private DBlite dBlite1 = new DBlite(this);; private ContentResolver contentResolver; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); //先對數據庫進行添加數據 dBlite1.add(email,username,date,sex); //經過contentResolver進行查找 contentResolver = TestWebviewDemo.this.getContentResolver(); Cursor cursor = contentResolver.query( RuiXin.CONTENT_URI, new String[] { RuiXin.EMAIL, RuiXin.USERNAME, RuiXin.DATE,RuiXin.SEX }, null, null, null); while (cursor.moveToNext()) { Toast.makeText( TestWebviewDemo.this, cursor.getString(cursor.getColumnIndex(RuiXin.EMAIL)) + " " + cursor.getString(cursor.getColumnIndex(RuiXin.USERNAME)) + " " + cursor.getString(cursor.getColumnIndex(RuiXin.DATE)) + " " + cursor.getString(cursor.getColumnIndex(RuiXin.SEX)), Toast.LENGTH_SHORT).show(); } startManagingCursor(cursor); //查找後關閉遊標 } }
注:上面是在一個程序中進行的測試,也能夠再新建一個工程來模擬一個新的程序,而後將上面查詢的代碼加到新的程序當中!這樣就模擬了contentprovider的數據共享功能了!
新建個工程:TestProvider
建立一個測試的activityide
public class Test extends Activity { /** Called when the activity is first created. */ private ContentResolver contentResolver; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); //經過contentResolver進行查找 contentResolver = TestWebviewDemo.this.getContentResolver(); Cursor cursor = contentResolver.query( RuiXin.CONTENT_URI, new String[] { RuiXin.EMAIL, RuiXin.USERNAME, RuiXin.DATE,RuiXin.SEX }, null, null, null); while (cursor.moveToNext()) { Toast.makeText(TestWebviewDemo.this, cursor.getString(cursor.getColumnIndex(RuiXin.EMAIL)) + " " + cursor.getString(cursor.getColumnIndex(RuiXin.USERNAME)) + " " + cursor.getString(cursor.getColumnIndex(RuiXin.DATE)) + " " + cursor.getString(cursor.getColumnIndex(RuiXin.SEX)), Toast.LENGTH_SHORT).show(); } startManagingCursor(cursor); //查找後關閉遊標 } }