自定义ContentProvider的使用实例与解析

本例中实现的流程是:contentResolver --> 自定义的contentProvider

具体到方法:contentResolver.insert() --> 自定义的contentProvider.insert() --> sqLiteDatabase.insert()

app12中,自定义的contentProvider

本例中仅实现了insert()功能

package com.clc.app12;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

public class MyProvider extends ContentProvider {
    private DBHelper dbHelper;

    //一加载MyProvider类就创建matcher对象
    private static UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);
    //并且将MyProvider管理的数据资源编号;
    //com.clc.app12.provider是MyProvider的字符串标识,其把管着stu表、user表
    //访问MyProvider的resolver中uri必须包含此标识
    static {
        matcher.addURI("com.clc.app12.provider","stu",1);
        matcher.addURI("com.clc.app12.provider","user",2);
    }

    @Override
    public boolean onCreate() {
        //实例化DBHelper,同时也创建了两个表
        dbHelper = new DBHelper(getContext(),"app12.db",null,1);
        return true;
    }

    @Nullable
    @Override
    public Cursor query(@NonNull Uri uri, @Nullable String[] strings, @Nullable String s, @Nullable String[] strings1, @Nullable String s1) {
        return null;
    }

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

    @Nullable
    @Override
    public Uri insert(@NonNull Uri uri, @Nullable ContentValues contentValues) {
        //涉及到SQLiteDatabase的内容,不是本篇的重点,暂时不探讨
        SQLiteDatabase db = dbHelper.getReadableDatabase();

        //matcher.match(uri)返回与uri匹配的int值,如果没有匹配则返回-1
        switch (matcher.match(uri)){
            case 1:
                //插入成功时,db.insert()返回新行主键值
                long rowId = db.insert("stu", null, contentValues);
                if (rowId > 0){
                    //将新纪录的行号接到uri尾部
                    Uri newUri = ContentUris.withAppendedId(uri, rowId);

                    //这行代码可用于通知所有注册在该Uri上的监听者,该ContentProvider所共享的数据发生了改变,跟resolver与provider之间的交互无关
                    getContext().getContentResolver().notifyChange(newUri,null);

                    //返回新uri,对应contentResolver.insert()的返回值
                    return newUri;
                }
                break;
            case 2:
                long rowId1 = db.insert("user", null, contentValues);
                if (rowId1 > 0){
                    Uri newUri = ContentUris.withAppendedId(uri, rowId1);
                    getContext().getContentResolver().notifyChange(newUri,null);
                    return newUri;
                }
                break;
            default:
                return null;
        }

        return null;
    }

    @Override
    public int delete(@NonNull Uri uri, @Nullable String s, @Nullable String[] strings) {
        return 0;
    }

    @Override
    public int update(@NonNull Uri uri, @Nullable ContentValues contentValues, @Nullable String s, @Nullable String[] strings) {
        return 0;
    }
}

app12中,注册provider

在<manifest>--<application>中添加

        <provider
            android:authorities="com.clc.app12.provider"
            android:name=".MyProvider"
            android:exported="true"
            />

app12中,自定义SQLiteOpenHelper

package com.clc.app12;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import androidx.annotation.Nullable;

public class DBHelper extends SQLiteOpenHelper {
    private String sqlCreateStu;
    private String sqlCreateUser;

    public DBHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
        //获取sql string资源
        sqlCreateStu = context.getString(R.string.sql_create_stu);
        sqlCreateUser = context.getString(R.string.sql_create_user);
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        //在创建DBHelper对象时就执行sql,创建表格
        sqLiteDatabase.execSQL(sqlCreateStu);
        sqLiteDatabase.execSQL(sqlCreateUser);
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

    }
}

app12中,定义建表sql

在values/strings.xml/<resources>中添加

    <string name="sql_create_stu">
        create table stu(
            id integer primary key autoincrement,
            name text,
            age integer
        )
    </string>
    <string name="sql_create_user">
        create table user(
            id integer primary key autoincrement,
            username text,
            password text
        )
    </string>

app13中,测试

本例中,仅测试insert(),

package com.clc.app13;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ContentValues;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

public class MainActivity extends AppCompatActivity {
    public static final String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        findViewById(R.id.btn_insert_stu).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ContentValues values = new ContentValues();
                values.put("name","tom");
                values.put("age",12);

                //向stu表插入记录
                //这里的uri相当于一个令牌
                //其中"com.clc.app12.provider"让对应的contentProvider可以同意resolver的操作请求
                //其中"stu"指定了要操作的数据,这里是个表
                Uri newUri = getContentResolver().insert(Uri.parse("content://com.clc.app12.provider/stu"), values);
                Log.d(TAG, "onClick: "+newUri);
            }
        });

        findViewById(R.id.btn_insert_user).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ContentValues values = new ContentValues();
                values.put("username","jack");
                values.put("password","123456");

                //向user表插入记录
                Uri newUri = getContentResolver().insert(Uri.parse("content://com.clc.app12.provider/user"), values);
                Log.d(TAG, "onClick: "+newUri);
            }
        });
    }
}

启动app12、app13......; 发现关闭app12,仍可插入数据

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值