本文是针对ContentProvider基础用法的模拟:
ContentProvider主要是用于将数据库变为provider提供给第三方使用的控件
本文将创建一个数据库,一个第三方使用者来演示如何使用该组件。
具体步骤:
四大组件都需要在manifest中进行注册
authority处一般来说填写的是包名,此处可以添加多个权限(但是后面的matcher中只能设置一个权限)
此处的exported表示其他应用也可读取的权限:
manifest中声明的provider中可以添加多个权限,但是此处只能放入一个参数!
注意!
规则中的path如果修改了,则在第三方应用中的URI也要添加上该path,这样才能通过校验(一般来说,path表示表名)
query方法根据权限来进行操作(如果匹配权限则进行query操作,如果不匹配则抛出异常)
button设置点击事件,先拿到一个contentresolver,创建一个URI,拿到对方的cursor再进行query操作:
再以insert为例:
ContentProvider中:
DAO接口:
public interface IUserDao {
/**
* 添加用户
* @param user
* @return
*/
long addUser(User user);
/**
* 删除用户
* @param
* @return
*/
int delUserById(int id);
/**
* 更新用户信息
* @param user
* @return
*/
int updateUser(User user);
/**
* 查询用户记录
* @param id
* @return
*/
User getUserById(int id);
/**
* 获取所有用户记录
* @param
* @return
*/
List<User> listAllUser();
}
DAO实现类:
public class UserDaoImpl implements IUserDao {
private final UserDatabaseHelper muserDatabaseHelper;
/**
* 构造方法,实例化数据库对象
* @param context
*/
public UserDaoImpl(Context context){
muserDatabaseHelper = new UserDatabaseHelper(context);
}
/**
* 插入user,db.insert的返回值是long类型的,返回的是行的ID,操作失败时返回-1
* @param user
* @return
*/
@Override
public long addUser(User user) {
SQLiteDatabase db=muserDatabaseHelper.getWritableDatabase();//获取数据库
ContentValues values=new ContentValues(); //键和键值的形式存入contextvalues中,ID是自动增长的故不用特地去设置
values.put(Constants.FILED_USER_NAME,user.getUserName());
values.put(Constants.FILED_USER_SEX,user.getSex());
values.put(Constants.FILED_PASSWORD,user.getPassword());
values.put(Constants.FILED_USER_AGE,user.getAge());
long result=db.insert(Constants.TABLE_NAME,null,values); //没有values就去创建一个contextvalues
db.close();
return result;
}
/**
* 删除user,根据ID删除,返回值也是一个int类型,返回的是删除的行数
*/
@Override
public int delUserById(int id) {
SQLiteDatabase db=muserDatabaseHelper.getWritableDatabase();//获取数据库
int result=db.delete(Constants.TABLE_NAME,Constants.FILED_ID+" =?",new String[]{
id + " "});
db.close();
return result;
}
/**
* 更新用户数据,根据id更新内容,返回值表示影响的行数
* @param user
* @return
*/
@Override
public int updateUser(User user) {
SQLiteDatabase db=muserDatabaseHelper.getWritableDatabase();//获取数据库
ContentValues values=new ContentValues();
values.put(Constants.FILED_USER_NAME,user.getUserName());
values.put(Constants.FILED_USER_SEX,user.getSex());
values.put(Constants.FILED_PASSWORD,user.getPassword());
values.put(Constants.FILED_USER_AGE,user.getAge());
int result=db.update(Constants.TABLE_NAME,values,Constants.FILED_ID+" =?",new String[]{
user.getId()+""});//需要有一个value的参数
db.close();
return result;
}
/**
* 查询
* @param id
* @return
*/
@Override
public User getUserById(int id) {
SQLiteDatabase db=muserDatabaseHelper.getWritableDatabase();//获取数据库
//sql语句查询
String sql="select *from "+Constants.TABLE_NAME+" where "+Constants.FILED_ID+" =?";//防止SQL注入使用一个加密符
Cursor cursor=db.rawQuery(sql,new String[]{
id+""});
User user=null;
if (cursor.moveToNext()){
//查询一个用if
user=new User(); //创建一个新的USER用来获取数据
//获取ID
int userID=cursor.getInt(cursor.getColumnIndex(Constants.FILED_ID));
user.setId(userID);
//获取username
String userName=cursor.getString(cursor.getColumnIndex(Constants.FILED_USER_NAME));
user.setUserName(userName);
//获取password
String password=cursor.getString(cursor.getColumnIndex(Constants.FILED_PASSWORD));
user.setPassword(password);
//获取sex
String sex=cursor.getString(cursor.getColumnIndex(Constants.FILED_USER_SEX));
user.setSex(sex);
//获取age
int age=cursor.getInt(cursor.getColumnIndex(Constants.FILED_USER_AGE));
user.setAge(age);
}
db.close();
return user;
}
@Override
public List<User> listAllUser() {
SQLiteDatabase db=muserDatabaseHelper.getWritableDatabase();//获取数据库
//因为查询所有用户,所以条件全是null
Cursor cursor=db.query(Constants.TABLE_NAME,null,null,null,null,null,null);
User user=null;
List<User> users=new ArrayList<>();
while (cursor.moveToNext()){
//查询多个用while
user=new User(); //创建一个新的USER用来获取数据
//获取ID
int userID=cursor.getInt(cursor.getColumnIndex(Constants.FILED_ID));
user.setId(userID);
//获取username
String userName=cursor.getString(cursor.getColumnIndex(Constants.FILED_USER_NAME));
user.setUserName(userName);
//获取password
String password=cursor.getString(cursor.getColumnIndex(Constants.FILED_PASSWORD));
user.setPassword(password);
//获取sex
String sex=cursor.getString(cursor.getColumnIndex(Constants.FILED_USER_SEX));
user.setSex(sex);
//获取age
int age=cursor.getInt(cursor.getColumnIndex(Constants.FILED_USER_AGE));
user.setAge(age);
users.add(user);
}
db.close();
return users;
}
}
bean类:
public class User {
private int id;
private String userName;
private String password;
private String sex;
private int age;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
/**
* 复写Tostring方法,将相关信息全部打印出来
* @return
*/
@Override
public String toString() {
return "User{" +
"id=" + id +
", userName='" + userName + '\'' +
", password='" + password + '\'' +
", sex='" + sex + '\'' +
", age=" + age +
'}';
}
}
databaseHelper:
public class UserDatabaseHelper extends SQLiteOpenHelper {
private static final String TAG ="UserDatabaseHelper" ;
public UserDatabaseHelper(@Nullable Context context) {
super(context, Constants.DATABASE_NAME, null, Constants.DB_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
//创建数据库
String createSQL="create table "+
Constants.TABLE_NAME+"("+
Constants.FILED_ID+" integer primary key autoincrement,"+
Constants.FILED_USER_NAME+" varchar(20),"+
Constants.FILED_PASSWORD+" varchar(32),"+
Constants.FILED_USER_SEX+" varchar(5),"+
Constants.FILED_USER_AGE+" integer)";
db.execSQL(createSQL);
Log.d(TAG,"create table......");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
provider:
public class UserProvider extends ContentProvider {
private static final String TAG ="UserProvider" ;
private UserDatabaseHelper mUserDatabaseHelper=null;
private static final int USER_MATCH_CODE=1;
private static UriMatcher uriMatcher=new UriMatcher(UriMatcher.NO_MATCH); //参数表示:当不匹配URI时的返回值
static {
//在静态代码块中添加相关规则
uriMatcher.addURI("com.example.contentprovider",null,USER_MATCH_CODE); //code表示如果匹配后的返回值
}
@Override
public boolean onCreate() {
mUserDatabaseHelper=new UserDatabaseHelper(getContext()); //在oncreate的时候创建helper
return false;
}
//根据Uri来判断权限是否匹配,所以需要一个校验URI的工具类
@Nullable
@Override
public Cursor query(@NonNull Uri uri, @Nullable String[] projection, @Nullable String selection, @Nullable String[] selectionArgs, @Nullable String sortOrder) {
int result=uriMatcher.match(uri);
if (result == USER_MATCH_CODE){
//此时说明匹配
SQLiteDatabase db=mUserDatabaseHelper.getWritableDatabase();
Cursor cursor=db.query(Constants.TABLE_NAME,projection,selection,selectionArgs,null,null,sortOrder);
return cursor;
}else{
//不匹配规则
throw new IllegalArgumentException("参数错误");
}
}
@Nullable
@Override
public String getType(@NonNull Uri uri) {
return null;
}
@Nullable
@Override
public Uri insert(@NonNull Uri uri, @Nullable ContentValues values) {
int result=uriMatcher.match(uri);
if (result == USER_MATCH_CODE){
//URI匹配时
SQLiteDatabase db=mUserDatabaseHelper.getWritableDatabase();
long id=db.insert(Constants.TABLE_NAME,null,values);
Uri resultUri=Uri.parse("content://com.example.contentprovider/user"+id);
Log.d(TAG,"insert user result is "+id);
//此时已经插入成功,数据已经变化了,所以要通知监听者
getContext().getContentResolver().notifyChange(resultUri,null);
return resultUri;
}else{
//不匹配时抛出异常
throw new IllegalArgumentException("参数错误");
}
}
@Override
public int delete(@NonNull Uri uri, @Nullable String selection, @Nullable String[] selectionArgs) {
return 0;
}
@Override
public int update(@NonNull Uri uri, @Nullable ContentValues values, @Nullable String selection, @Nullable String[] selectionArgs) {
return 0;
}
}
constants:
public class Constants {
public static final String DATABASE_NAME="provider.db";
public static final int DB_VERSION=1; public static final String FILED_USER_NAME="username";
public static final String FILED_PASSWORD="password";
public static final String FILED_USER_AGE="age";
public static final String FILED_USER_SEX="sex";
public static final String TABLE_NAME="user";
public static final String FILED_ID="_id";
}
TestProvider中
constants:
public class Constants {
public static final String FILED_USER_NAME="username";
public static final String FILED_PASSWORD="password";
public static final String FILED_USER_AGE="age";
public static final String FILED_USER_SEX="sex";
}
mainActivity:
public class MainActivity extends AppCompatActivity {
private static final String TAG ="MainActivity" ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ContentResolver contentResolver=getContentResolver();
Uri uri= Uri.parse("content://com.example.contentprovider");
contentResolver.registerContentObserver(uri, true, new ContentObserver(new Handler()) {
@Override
public void onChange(boolean selfChange) {
super.onChange(selfChange);
Log.d(TAG,"用户数据发生改变");
}
});
}
/**
* 点击的时候去获取user信息
* @param view
*/
public void getUserData(View view ){
ContentResolver contentResolver=getContentResolver();
Uri uri= Uri.parse("content://com.example.contentprovider");
Cursor cursor=contentResolver.query(uri,null,"userName=?",new String[]{
"yangyang"},null);
String[] columnNames=cursor.getColumnNames();
for (String columnName : columnNames) {
Log.d(TAG,"columnNames "+columnName);
}
while (cursor.moveToNext()) {
Log.d(TAG,"————————————");
for (String columnName : columnNames) {
String value=cursor.getString(cursor.getColumnIndex(columnName));
Log.d(TAG,"value is "+value);
}
}
cursor.close();
}
/**
* 添加user
* @param view
*/
public void addUser(View view){
ContentResolver contentResolver=getContentResolver();
Uri urii=Uri.parse("content://com.example.contentprovider/user");
ContentValues values=new ContentValues();
values.put(Constants.FILED_USER_NAME,"jiejie");
values.put(Constants.FILED_PASSWORD,"123456");
values.put(Constants.FILED_USER_SEX,"男");
values.put(Constants.FILED_USER_AGE,20);
contentResolver.insert(urii,values);
}
}