目录
一、实验内容
存在两个app,ContentProvider和Myresolver.
其中,ContentProvider创建数据库,并提供接口,使得Myresolver可以实现对数据库的插入。
二、代码实现
一个程序可以通过实现一个ContentProvider的抽象接口将自己的数据完全暴露出去,而且ContentProviders是以类似数据库中表的方式将数据暴露,也就是说ContentProvider就像一个“数据库”。那么外界获取其提供的数据,也就应该与从数据库中获取数据的操作基本一样,只不过是采用URI来表示外界需要访问的“数据库”。
在ContentProvider里注册
<provider
android:name=".MyContentProvider"
android:authorities="cjy.provider2"
android:enabled="true"
android:exported="true"></provider>
ContentProvider:
MyDAO:
public class MyDAO {
private SQLiteDatabase database;
private MyDBhelper dBhelper;
private Context context;
public MyDAO(Context context) {
this.context = context;
//创建数据库
dBhelper = new MyDBhelper(context, "cjyDB", null, 1);
database = dBhelper.getWritableDatabase();
}
//自定义uri
public Uri cjyInsert(){
ContentValues value1=new ContentValues();
value1.put("name","cjy");
value1.put("age","20");
Uri insertUri;
Uri uri=Uri.parse("content://cjy.provider2/student");
long RowId=database.insert("student",null,value1);
insertUri= ContentUris.withAppendedId(uri,RowId);
return insertUri;
}
}
mycontentprovider:
private MyDAO myDAO;
private Context context;
@Override
public boolean onCreate() {
context=this.getContext();
myDAO=new MyDAO(context);
return true;
}
@Override
public Uri insert(Uri uri, ContentValues values) {
// TODO: Implement this to handle requests to insert a new row.
return myDAO.cjyInsert();
}
Myresolver:
private static final String AUTHORITY="cjy.Provider2";
private static final Uri NOTIFY_URI=Uri.parse("content://"+AUTHORITY+"/student");
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button1=findViewById(R.id.button_i);
Button button2=findViewById(R.id.button_u);
Button button3=findViewById(R.id.button_q);
Button button4=findViewById(R.id.button_d);
ContentResolver resolver=getContentResolver();
//把表变成uri格式的表
Uri uri=Uri.parse("content://cjy.provider2/student");
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ContentValues value1=new ContentValues();
value1.put("name","cjy");
value1.put("age",20);
resolver.insert(uri,value1);
}
});
三、结果展示
之前:
之后: