Android ContentProvider基本使用

一、基本概念:

1.ContentProvider为存储和获取数据提供了统一的接口;
2.使用ContentProvider可以在不同的应用程序之间共享数据;
3.Android为常见的一些数据提供了ContentProvider(包括音频、视频、图片和通讯录等等 )

直接贴下代码:

定义数据库帮助类:

public class DbOpenHelper extends SQLiteOpenHelper {

    //数据库名称
    private static final String DATA_BASE_NAME = "people.db";

    //数据库版本号
    private static final int DATE_BASE_VERSION = 1;

    //表名-男孩
    public static final String BOY_TABLE_NAME = "boy";

    //表名-女孩
    public static final String GIRL_TABLE_NAME = "girl";

    //创建表-男孩(两列:主键自增长、姓名)
    private final String CREATE_BOY_TABLE = "create table " + BOY_TABLE_NAME + "(_id integer primary key autoincrement, name text)";

    //创建表-女孩(两列:主键自增长、姓名)
    private final String CREATE_GIRL_TABLE = "create table " + GIRL_TABLE_NAME + "(_id integer primary key autoincrement, name text)";

    public DbOpenHelper(Context context) {
        super(context, DATA_BASE_NAME, null, DATE_BASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_BOY_TABLE);//创建男孩表
        db.execSQL(CREATE_GIRL_TABLE);//创建女孩表
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        //一些数据库升级操作
    }
}

内容提供者:

public class MyFirstContentProvider extends ContentProvider {

    private Context context;

    private SQLiteDatabase sqLiteDatabase;

    public static final String AUTHORITY = "com.zyc.hezuo.contentproviderdemo.MyFirstContentProvider";

    public static final int BOY_URI_CODE = 0;

    public static final int GIRL_URI_CODE = 1;

    private static final UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);

    static {
        uriMatcher.addURI(AUTHORITY, DbOpenHelper.BOY_TABLE_NAME, BOY_URI_CODE);
        uriMatcher.addURI(AUTHORITY, DbOpenHelper.GIRL_TABLE_NAME, GIRL_URI_CODE);
    }

    /**
     * 获取表名
     * @param uri
     * @return
     */
    private String getTableName(Uri uri) {
        String tableName = null;
        switch (uriMatcher.match(uri)) {
            case BOY_URI_CODE:
                tableName = DbOpenHelper.BOY_TABLE_NAME;
                break;
            case GIRL_URI_CODE:
                tableName = DbOpenHelper.GIRL_TABLE_NAME;
                break;
        }
        return tableName;
    }



    @Override
    public boolean onCreate() {
        context = getContext();
        initProviderData();
        return false;
    }

    //初始化原始数据
    private void initProviderData() {
        sqLiteDatabase = new DbOpenHelper(context).getWritableDatabase();
        sqLiteDatabase.beginTransaction();
        ContentValues contentValues = new ContentValues();
        contentValues.put("name", "男孩1");
        sqLiteDatabase.insert(DbOpenHelper.BOY_TABLE_NAME, null, contentValues);
        contentValues.put("name", "男孩2");
        sqLiteDatabase.insert(DbOpenHelper.BOY_TABLE_NAME, null, contentValues);
        contentValues.put("name", "男孩3");
        sqLiteDatabase.insert(DbOpenHelper.BOY_TABLE_NAME, null, contentValues);
        contentValues.clear();

        contentValues.put("name", "女孩1");
        sqLiteDatabase.insert(DbOpenHelper.GIRL_TABLE_NAME, null, contentValues);
        contentValues.put("name", "女孩2");
        sqLiteDatabase.insert(DbOpenHelper.GIRL_TABLE_NAME, null, contentValues);
        contentValues.put("name", "女孩3");
        sqLiteDatabase.insert(DbOpenHelper.GIRL_TABLE_NAME, null, contentValues);
        sqLiteDatabase.setTransactionSuccessful();
        sqLiteDatabase.endTransaction();
    }

    @Nullable
    @Override
    public Cursor query(@NonNull Uri uri, @Nullable String[] projection, @Nullable String selection, @Nullable String[] selectionArgs, @Nullable String sortOrder) {
        String tableName = getTableName(uri);
        if (TextUtils.isEmpty(tableName)) {
            throw new IllegalArgumentException("Unsupported URI:" + uri);
        }
        return sqLiteDatabase.query(tableName, projection, selection, selectionArgs, null, null, sortOrder);
    }

    @Nullable
    @Override
    public String getType(@NonNull Uri uri) {
        return null;
    }

    @Nullable
    @Override
    public Uri insert(@NonNull Uri uri, @Nullable ContentValues values) {
        String tableName = getTableName(uri);
        if(TextUtils.isEmpty(tableName)){
            throw new IllegalArgumentException("Unsupported URI:" + uri);
        }
        sqLiteDatabase.insert(tableName, null, values);
        context.getContentResolver().notifyChange(uri, null);
        return uri;
    }

    @Override
    public int delete(@NonNull Uri uri, @Nullable String selection, @Nullable String[] selectionArgs) {
        String tableName = getTableName(uri);
        if (TextUtils.isEmpty(tableName)) {
            throw new IllegalArgumentException("Unsupported URI:" + uri);
        }
        int count = sqLiteDatabase.delete(tableName, selection, selectionArgs);
        if (count > 0) {
            context.getContentResolver().notifyChange(uri, null);
        }
        return count;
    }

    @Override
    public int update(@NonNull Uri uri, @Nullable ContentValues values, @Nullable String selection, @Nullable String[] selectionArgs) {
        String tableName = getTableName(uri);
        if (TextUtils.isEmpty(tableName)) {
            throw new IllegalArgumentException("Unsupported URI:" + uri);
        }
        int row = sqLiteDatabase.update(tableName, values, selection, selectionArgs);
        if (row > 0) {
            context.getContentResolver().notifyChange(uri, null);
        }
        return row;
    }
}

注册内容提供者:

    <provider
        android:name=".MyFirstContentProvider"
        android:exported="true"
        android:authorities="com.zyc.hezuo.contentproviderdemo.MyFirstContentProvider" />

使用:

    Uri boyUri = Uri.parse("content://com.zyc.hezuo.contentproviderdemo.MyFirstContentProvider/boy");

    ContentValues contentValues = new ContentValues();
    contentValues.put("name", "张三");
    //getContentResolver().insert(boyUri, contentValues);
    //getContentResolver().delete(boyUri, )
    Cursor boyCursor = getContentResolver().query(boyUri, new String[]{"_id", "name"}, null, null, null);
    if (boyCursor != null) {
        while (boyCursor.moveToNext()) {
            Log.e("yunchong", "ID:" + boyCursor.getInt(boyCursor.getColumnIndex("_id")) + "  name:" + boyCursor.getString(boyCursor.getColumnIndex("name")));
        }
        boyCursor.close();
    }

    Uri girlUri = Uri.parse("content://com.zyc.hezuo.contentproviderdemo.MyFirstContentProvider/girl");
    contentValues.clear();
    //contentValues.put("name", "李四");
    //getContentResolver().insert(girlUri, contentValues);
    Cursor girlCursor = getContentResolver().query(girlUri, new String[]{"_id", "name"}, null, null, null);
    if (girlCursor != null) {
        while (girlCursor.moveToNext()) {
            Log.e("yunchong", "ID:" + girlCursor.getInt(girlCursor.getColumnIndex("_id"))
                    + "  name:" + girlCursor.getString(girlCursor.getColumnIndex("name")));
        }
        girlCursor.close();
    }

由于时间比较仓促,后续会继续更新!

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容