Android基礎知識元件篇---------ContentProvider
ContentProvider 主要用於在不同的程式之間實現資料共享
一、內容提供器的用法
一種是使用現有的內容提供器來讀取和操作相應程式中的資料
一種是建立自己的內容提供器給我們的程式的資料提供外部介面
二、怎樣訪問內容提供器中的資料
藉助ContentResolver類,通過Context的getContentResolver()方法獲取到該類的例項
ContentResolver中提供了一系列的方法對資料進行CRUD操作,insert()插入 update()更新 delete()刪除 query()查詢
ContentResolver中的增刪改查方法是不接受表名引數的,用一個Uri引數替代。可以呼叫Uri.parse()方法將內容URI字串解析成Uri物件。
Cursor cursor=getContentResolver().query(uri,projection,selection,selectionArgs,sortOrder ); 查詢完以後返回的仍然是一個Cursor物件,這個時候可以將物件中的資料資料讀取出來。
query()方法中引數的含義:
uri 指定查詢某一個應用程式下的某張表 projection 指定查詢的列名 selection 指定where的約束條件
selectionArgs 為where中的佔位符提供具體的值 orderBy 指定查詢結果的排序方式
取出query()中的資料:
if(cursor!=null){
while(cursor.moveToNext()){
String xxx=cursor.getString(cursor.getColumnIndex(" "));
}
cursor.close();
}
三、怎樣向表中新增資料
將新增的資料組裝到 ContentValues中,然後在呼叫ContentResolver的insert()方法。
/**
ContentValues values= new ContentValues();
values.put(" ", );
values.put(" ",)
getContentResolver().insert(uri,values);
**/
同樣更新的話也是這樣
四、建立自己的內容提供器
新建一個類繼承自ContentProvider
package com.example.administrator.mylmada; import android.content.ContentProvider; import android.content.ContentValues; import android.content.UriMatcher; import android.database.Cursor; import android.net.Uri; public class MyProvider extends ContentProvider { public static final int TABLE1_DIR=0; public static final int TABLE1_ITEM=1; public static final int TABLE2_DIR=2; public static final int TABLE2_ITEM=3; static { UriMatcher uriMatcher=new UriMatcher(UriMatcher.NO_MATCH); uriMatcher.addURI("","",TABLE1_DIR); uriMatcher.addURI("","",TABLE1_ITEM); uriMatcher.addURI("","",TABLE2_DIR); uriMatcher.addURI("","",TABLE2_ITEM); } @Override public boolean onCreate() { return false; } @androidx.annotation.Nullable @Override public Cursor query(@androidx.annotation.NonNull Uri uri, @androidx.annotation.Nullable String[] projection, @androidx.annotation.Nullable String selection, @androidx.annotation.Nullable String[] selectionArgs, @androidx.annotation.Nullable String sortOrder) { //具體的邏輯 return null; } @androidx.annotation.Nullable @Override public String getType(@androidx.annotation.NonNull Uri uri) { switch(uriMacher.match(uri)){ //具體的邏輯 } return null; } @androidx.annotation.Nullable @Override public Uri insert(@androidx.annotation.NonNull Uri uri, @androidx.annotation.Nullable ContentValues values) { //具體的邏輯 return null; } @Override public int delete(@androidx.annotation.NonNull Uri uri, @androidx.annotation.Nullable String selection, @androidx.annotation.Nullable String[] selectionArgs) { //具體的邏輯 return 0; } @Override public int update(@androidx.annotation.NonNull Uri uri, @androidx.annotation.Nullable ContentValues values, @androidx.annotation.Nullable String selection, @androidx.annotation.Nullable String[] selectionArgs) { //具體的邏輯 return 0; } }
這樣我們就將自己的資料共享給其他程式了。