使用ContentProvider类进行数据获取
文件数据、数据库数据以及一些其它类型的数据在android中都是私有的,在android中,并没有提供所有应用共同访问的公共储存区域。但各应用程序间通常需要进行数据共享,如联系人信息等。
ContentProvider类
创建一个MyDBhelper帮助类
若要进行对数据库的操作,必须使用SQLiteDatebase类,因为各种操作都是封装到SQLiteDatebase类中的,在MyDB类中进行建表语句,建立一个student学生表
public Mydbhelp(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);//super是什么意思
}
@Override
// 建表是sql语句,数据库中的各种操作都是是封装在SQLiteDatebase类中的,必须在onCreat中写
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL("create table student" +
"(id integer primary key autoincrement," +
"name varchar(20),age integer)");
}
创建DAO类
在android中,应用程序可以实现Content Provider的抽象接口从而将自己的数据暴露出去。Content Provider拥有一套通用的方法来实现对数据的增、删、改、查功能。DAO类即为数据访问接口,当需要访问数据库时,不用再单独和数据库建立连接,使用DAO类操作数据库即可。
public class MyDAO {
SQLiteDatabase database;
Context context;
public MyDAO(Context context)
{this.context=context;
Mydbhelp mydbhelp=new Mydbhelp(context,"student",null,1);
database=mydbhelp.getWritableDatabase();}
public Uri zyjInsert(ContentValues contentValues)
{
ContentValues values2=new ContentValues();
values2.put("name","zyj");
values2.put("age",20);
// 要操作哪个路径呢?
long rowId=database.insert("student",null,values2);
Uri uri=Uri.parse("content://myprovider/student");
// withAppendedId用于将uri和ID连接起来组成新路径
Uri inserturi= ContentUris.withAppendedId(uri,rowId);
context.getContentResolver().notifyChange(inserturi,null);
return inserturi;
}
}
在Manifest.xml中定义authorities
<provider
android:name=".MyContentProvider"
android:authorities="myprovider"
android:enabled="true"
android:exported="true"></provider>
ContentResolver类
创建一个button,实现点击之后向数据库中添加数据,实现两个APP的数据库共享。找到目标App的路径,通过Uri的parse()方法将路径解析为要操作的数据,实现对数据库的操作。
public class MainActivity extends AppCompatActivity {
private Button button;
private ContentResolver contentResolver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button=findViewById(R.id.button);
contentResolver=getContentResolver();
// 将路径解析成要操作的数据
Uri uri=Uri.parse("content://myprovider/student");
ContentValues values=new ContentValues();
values.put("name","zyj");
values.put("age",20);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
contentResolver.insert(uri,values);
}
});
}
}