ContentProvider使用详解

概述

Android提供专门用于不同应用间进行数据共享的方式,底层实现是Binder,但是使用的过程比AIDL简单许多。主要用于第三方应用访问本应用的数据库中的数据。Contentprovider中有六个方法,分别是

  • query,update,insert,delete.(CRUD)就不多说了
  • getType:用来返回一个Uri请求所对应的的MIME类型(媒体型),比如图片,视频等
  • oncreate:表示ContentProvider的创建,一般用来初始化一些参数
    下面进行简单的演示
    1、首先创建一个BooksProvider类继承ContentProvider,重写上面所说的6个方法
BooksProvider extends ContentProvider {
    public static final String TAG = "BooksProviders";
    @Override
    public boolean onCreate() {
        Log.d(TAG,"onCerate,current thread:"+Thread.currentThread().getName());
        return true;
    }

    @Nullable
    @Override
    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
        Log.d(TAG,"query,current thread:"+Thread.currentThread().getName());
        return null;
    }

    @Nullable
    @Override
    public String getType(Uri uri) {
        Log.d(TAG,"getType,current thread:"+Thread.currentThread().getName());
        return null;
    }

    @Nullable
    @Override
    public Uri insert(Uri uri, ContentValues values) {
        Log.d(TAG,"insert,current thread:"+Thread.currentThread().getName());
        return null;
    }

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        Log.d(TAG,"delete,current thread:"+Thread.currentThread().getName());
        return null;
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
        Log.d(TAG,"update,current thread:"+Thread.currentThread().getName());
        return 0;
    }
}

2、我们需要在主菜单中注册这个BooksProvider,其中android:authorities是Contenprovider的唯一标识,通过这个属性,外部应用可以访问到我们的BookProvider,还可以给他添加权限,这样外部应用访问时,也必须要申请此权限才能访问(android:premisson)


        

3、接下来我们通过ContentResolver对象的query()方法去查询BookProvider中的数据,其中我们的com.example.ticker.bookprovider.BooksProvider就是唯一的标识

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Uri uri = Uri.parse("content://com.example.ticker.bookprovider.BooksProvider");
        getContentResolver().query(uri,null,null,null,null);
    }
}

运行下应用,我们可以在日记窗口看到如下信息


到这里,ContentProvider就已经基本完成了。接下来演示外部应用通过BookProvider访问本应用的图书信息。为了更好演示效果
1、先创建一个简单的数据库,代码如下


public class DbOpenHelper extends SQLiteOpenHelper {
    private static final String DB_NAME = "book_provider.db";
    public static final String BOOK_TABLE_NAME = "book";
    public static final String USER_TABLE_NAME = "user";
    private static final int DB_VWESION = 1;
    private String CREATE_BOOK_TABLE = "CREATE TABLE IF NOT EXISTS "+ BOOK_TABLE_NAME + "(id integer primary key autoincrement,name varchar(30))";
    private String CREATE_USER_TABLE = "CREATE TABLE IF NOT EXISTS "+USER_TABLE_NAME+"(id integer  primary key autoincrement,name varchar(30),sex integer)";
    public DbOpenHelper(Context context) {
        super(context, DB_NAME, null, DB_VWESION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_BOOK_TABLE);
        db.execSQL(CREATE_USER_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }
}

2、contentprovider通过URI来区分外界要访问的数据集合,为了知道外界访问的是哪个表,我们需要单独的URI和RUI_CODE并将Uri和对应的URI_CODE相关联。这样外界在请求的时候,我们就能知道访问的是哪个表

public class BookProvider extends ContentProvider {
    public static final String TAG = "BooksProviders";
    public static final String AUTHORITY = "com.example.ticker.bookprovider.BooksProvider";
    public static final Uri BOOK_CONTENT_URI = Uri.parse("content://"+AUTHORITY+"/book");
    public static final Uri USER_CONTENT_URI = Uri.parse("content://"+AUTHORITY+"/user");
    public static final int BOOK_URI_CODE = 0;
    public static final int USER_URI_CODE =1;
    private static final UriMatcher sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
    static{
        sUriMatcher.addURI(AUTHORITY,"book",BOOK_URI_CODE);
        sUriMatcher.addURI(AUTHORITY,"user",USER_URI_CODE);
    }
    .......
}

我们分别为book表和user表指定了Uri.

book对应“content://com.example.ticker.bookprovider.BooksProvider/book”
user对应“content://com.example.ticker.bookprovider.BooksProvider/user”

通过sUriMatcher.addURI()方法将其关联起来
3、将Uri和Uri_Code管理后,我们可以通过如下方式获取外界所要访问的数据源,根据Uri先取出Uri_Code,再根据Uri_Code获取数据表的名称

  private String getTableName(Uri uri){
        String tableName=null;
        switch (sUriMatcher.match(uri)){
            case BOOK_URI_CODE:
                tableName = DbOpenHelper.BOOK_TABLE_NAME;
                break;
            case USER_URI_CODE:
                tableName = DbOpenHelper.USER_TABLE_NAME;
                break;
            default:
                break;
        }return tableName;
    }

4、接下来就可以实现CURD方法了,首先从Uri中取出外界要访问的表的名称,然后根据外界传递的查询参数进行数据库查询操作

  @Nullable
    @Override
    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
        Log.d(TAG,"query,current thread:"+Thread.currentThread().getName());
        String table = getTableName(uri);
        if (table==null)
        {
            throw new IllegalArgumentException("Unsupported URI:"+uri);
        }
        return mDb.query(table,projection,selection,selectionArgs,null,null,sortOrder,null);
    }

另外需要注意,update、insert和delete方法会引起数据源的改变,所以需要通过ContentResolver的notifyChange()方法来通知外界ContentProvider中数据发生了改变。要观察一个ContentProvider中的数据改变情况,可以通过ContentResolver的registerContentOberver方法来注册观察这,通过unregisterContentObserver方法来解除观。
下面是BookProvider完整代码

public class
BooksProvider extends ContentProvider {
    public static final String TAG = "BooksProviders";
    public static final String AUTHORITY = "com.example.ticker.bookprovider.BooksProvider";
    public static final Uri BOOK_CONTENT_URI = Uri.parse("content://"+AUTHORITY +"/book");
    public static final Uri USER_CONTENT_URI = Uri.parse("content://"+AUTHORITY +"/user");
    public static final int BOOK_URI_CODE = 0;
    public static final int USER_URI_CODE = 1;
    private static final UriMatcher sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
    private SQLiteDatabase mDb;
    private Context mContext;
    static{
        sUriMatcher.addURI(AUTHORITY,"book",BOOK_URI_CODE);
        sUriMatcher.addURI(AUTHORITY,"user",USER_URI_CODE);
    }
    @Override
    public boolean onCreate() {
        Log.d(TAG,"onCerate,current thread:"+Thread.currentThread().getName());
        mContext = getContext();
        initProviderData();
        return true;
    }
    private void initProviderData(){
        mDb = new DbOpenHelper(mContext).getWritableDatabase();
        mDb.execSQL("delete from "+DbOpenHelper.BOOK_TABLE_NAME);
        mDb.execSQL("delete from "+DbOpenHelper.USER_TABLE_NAME);
        mDb.execSQL("insert into book values(3,'android ');");
        mDb.execSQL("insert into book values(4,'ios ');");
        mDb.execSQL("insert into book values(5,'Html5 ');");
        mDb.execSQL("insert into user values(1,'jake ',1);");
        mDb.execSQL("insert into user values(2,'jasmine ',0);");
    }

    @Nullable
    @Override
    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
        Log.d(TAG,"query,current thread:"+Thread.currentThread().getName());
        String table = getTableName(uri);
        if (table==null)
        {
            throw new IllegalArgumentException("Unsupported URI:"+uri);
        }
        return mDb.query(table,projection,selection,selectionArgs,null,null,sortOrder,null);
    }

    @Nullable
    @Override
    public String getType(Uri uri) {
        Log.d(TAG,"getType,current thread:"+Thread.currentThread().getName());
        return null;
    }

    @Nullable
    @Override
    public Uri insert(Uri uri, ContentValues values) {
        Log.d(TAG,"insert,current thread:"+Thread.currentThread().getName());
        String table = getTableName(uri);
        if (table==null){
            throw new IllegalArgumentException("Unsupport URI");
        }
        mDb.insert(table,null,values);
        mContext.getContentResolver().notifyChange(uri,null);
        return uri;
    }

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        Log.d(TAG,"delete,current thread:"+Thread.currentThread().getName());
        String table = getTableName(uri);
        if (table==null){
            throw new IllegalArgumentException("Unsupport URI");
        }
        int count = mDb.delete(table,selection,selectionArgs);
        if (count>0){
            getContext().getContentResolver().notifyChange(uri,null);
        }
        return count;
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
        Log.d(TAG,"update,current thread:"+Thread.currentThread().getName());
        String table  = getTableName(uri);
        if (table==null){
            throw new IllegalArgumentException("Unsupport URI");
        }
        int row = mDb.update(table,values,selection,selectionArgs);
        if (row>0){
            getContext().getContentResolver().notifyChange(uri,null);
        }
        return row;
    }
    private String getTableName(Uri uri){
        String tableName=null;
        switch (sUriMatcher.match(uri)){
            case BOOK_URI_CODE:
                tableName = DbOpenHelper.BOOK_TABLE_NAME;
                break;
            case USER_URI_CODE:
                tableName = DbOpenHelper.USER_TABLE_NAME;
                break;
            default:
                break;
        }return tableName;
    }
}

5、最后我们通过外部访问,看是否能出现我们预期的效果

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    public void onclick(View view){
        Uri uri = Uri.parse("content://com.example.ticker.bookprovider.BooksProvider/book");
        ContentValues values = new ContentValues();
        values.put("id",6);
        values.put("name","程序设计艺术");
        getContentResolver().insert(uri,values);
        Cursor bookCursor = getContentResolver().query(uri,new String[]{"id","name"},null,null,null);
        while(bookCursor.moveToNext()){
            Books book = new Books();
            book.setId(bookCursor.getInt(0));
            book.setName(bookCursor.getString(1));
            Log.d(BooksProvider.TAG,"query book id:"+book.getId()+" book name:" + book.getName());
        }
        bookCursor.close();
        Uri userUri = Uri.parse("content://com.example.ticker.bookprovider.BooksProvider//user");
        Cursor userCursor = getContentResolver().query(userUri,new String[]{"id","name","sex"},null,null,null);
        while(userCursor.moveToNext()){
            User user = new User();
            user.setId(userCursor.getInt(0));
            user.setName(userCursor.getString(1));
            user.setSex(userCursor.getInt(2));
            Log.d(BooksProvider.TAG,"query user id:"+user.getId()+" name:"+user.getName()+" sex:"+user.getSex());
        }
        userCursor.close();
    }
}

效果下图

ContentProvider使用详解_第1张图片

案例地址:
ContentProvider简单实例

学习资料
Android开发艺术探索

你可能感兴趣的:(ContentProvider使用详解)