关于contentProvider的简单使用

参考链接Android:关于ContentProvider的知识都在这里了!

使用步骤为:

1、创建数据库类DBHelper,继承自SQLiteOpenHelper
用于创建数据库和数据表,以及进行数据库相关操作(操作被自定义的contentProvider封装),需重写onCreate和onUpgrade方法

2、自定义contentProvider类,继承自contentProvider

a、新建DBHelper对象,即数据库和数据表 
mDbHelper = new DBHelper(getContext());
b、注册URI(通常与上一步创建的数据表对应)
static{
        mMatcher = new UriMatcher(UriMatcher.NO_MATCH);
        // 初始化
        mMatcher.addURI(AUTOHORITY,"user", User_Code);
        mMatcher.addURI(AUTOHORITY, "job", Job_Code);
        // 若URI资源路径 = content://cn.scu.myprovider/user ,则返回注册码User_Code
        // 若URI资源路径 = content://cn.scu.myprovider/job ,则返回注册码Job_Code
        // 根据返回的注册码方法决定对哪个数据表进行操作
    }
c、重写6个方法,并在方法中根据URI操作对应的数据表对象
/**
* 查询数据
*/
    @Override
    public Cursor query(Uri uri, String[] projection, String selection,
                        String[] selectionArgs, String sortOrder) {

        // 根据URI匹配 URI_CODE,从而匹配ContentProvider中相应的表名
        String table = getTableName(uri);

        // 查询数据
        return db.query(table,projection,selection,selectionArgs,null,null,sortOrder,null);
    }

3、在maniFest中注册contentProvider

4、在其他地方使用contentProvider
新建resolver对象,该对象可以基于URI自动调用对应contentProvider的方法操作数据

// 新建ContentResolver
ContentResolver resolver =  getContentResolver();
// 通过ContentResolver 根据URI 向ContentProvider中插入数据
resolver.insert(uri_user,values); //实际上会调用contentProvider中对应的方法

猜你喜欢

转载自blog.csdn.net/u012075670/article/details/81302945