AndroidManifest绑定依赖库
<provider
android:name=".StudentProvider"
android:authorities="com.mymusic.SQLiteStudent2.provider"
android:enabled="true"
android:exported="true">
provider>
添加一条固定消息
SQLiteTeacher添加消息,显示在SQLiteStudent数据库里
SQLiteStudent继承ContentProvider
在insert中添加代码
public Uri insert(@NonNull Uri uri, @Nullable ContentValues values) {
Log.e(TAG,"insert^^^^^^^^^^^^^^^^^^^^^^^^");
DBHelper dbHelper=new DBHelper(getContext(),"student_db",null,1);
SQLiteDatabase sqLiteDatabase=dbHelper.getWritableDatabase();
ContentValues v=new ContentValues();
v.put("name","zhangsan");
sqLiteDatabase.insert("student",null,v);
return null;
}
在SQLiteTeacher监听按钮,使用ContentResolver
public void onClick(View v) {
switch (v.getId()){
case R.id.test_btn:
Uri uri=Uri.parse("content://com.mymusic.SQLiteStudent2.provider");
ContentResolver resolver=getContentResolver();
ContentValues values=new ContentValues();
values.put("name",ContentValues);
resolver.insert(uri,values);
break;
输入框添加消息,添加入数据库
SQLiteStudent继承ContentProvider
在insert中添加代码
public Uri insert(@NonNull Uri uri, @Nullable ContentValues values) {
Log.e(TAG,"insert^^^^^^^^^^^^^^^^^^^^^^^^");
DBHelper dbHelper=new DBHelper(getContext(),"student_db",null,1);
SQLiteDatabase sqLiteDatabase=dbHelper.getWritableDatabase();
sqLiteDatabase.insert("student",null,values);
return null;
}
在SQLiteTeacher监听按钮,使用ContentResolver
public void onClick(View v) {
switch (v.getId()){
case R.id.test_btn:
String name=shuruEt.getText().toString();
Uri uri=Uri.parse("content://com.mymusic.SQLiteStudent2.provider");
ContentResolver resolver=getContentResolver();
ContentValues values=new ContentValues();
values.put("name",name);
resolver.insert(uri,values);
break;
避免进行初始化,放置了静态代码块
SQLiteStudent
private String TAG="StudentProvider";
private DBHelper dbHelper;
public static final int STUDENT=0;
public static final int STUDENT_ITEM=1;
public static final int TEACHER=2;
public static final int TEACHER_ITEM=3;
private static final String AUTHORITY="com.mymusic.SQLiteStudent2.provider";
private static UriMatcher uriMatcher;
//静态代码块
static {
uriMatcher = new UriMatcher(uriMatcher.NO_MATCH);
uriMatcher.addURI("com.mymusic.SQLiteStudent2.provider", "student", STUDENT);
uriMatcher.addURI("com.mymusic.SQLiteStudent2.provider", "student/#", STUDENT_ITEM);
uriMatcher.addURI("com.mymusic.SQLiteStudent2.provider", "teacher", TEACHER);
uriMatcher.addURI("com.mymusic.SQLiteStudent2.provider", "teacher/#", TEACHER_ITEM);//添加规格
}