在一个存在数据库的应用中定义一个内容提供者contentprovider
public class DatabaseProvider extends ContentProvider {//定义一个类继承内容提供者
/*
BOOK_DIR:book表全部数据
BOOk_ITEM:book表一条数据
AUTHORITY:代表uri
*/
public static final int BOOK_DIR=0;
public static final int BOOk_ITEM=1;
private static final String AUTHORITY="text.sqlitedatabase.provider";
private static UriMatcher uriMatcher;
private MyDatabaseHelper dbhelper;
static {//利用静态代码块定义uri
uriMatcher=new UriMatcher(UriMatcher.NO_MATCH);
uriMatcher.addURI(AUTHORITY,"Book",BOOK_DIR);
uriMatcher.addURI(AUTHORITY,"Book/#",BOOk_ITEM);
}
@Override
public boolean onCreate() {
dbhelper=new MyDatabaseHelper(getContext(),"BookStore.db",null,2);
通过数据库帮助类拿到一个新的数据库
return true;
}
@Nullable
@Override
---helper拿到数据库进行查询
public Cursor query(@NonNull Uri uri, @Nullable String[] strings, @Nullable String s, @Nullable String[] strings1, @Nullable String s1) {
SQLiteDatabase db=dbhelper.getReadableDatabase();
Cursor cursor=null;
switch (uriMatcher.match(uri)){//根据uri判断调用那个
case BOOK_DIR:数据库query操作
cursor=db.query("Book",strings,s,strings1,null,null,s1);
break;
case BOOk_ITEM:
String id=uri.getPathSegments().get(1);
cursor= db.query("Book",strings,"id=?",new String[]{id},null,null,s1);
break;
}
return cursor;返回一个cursor
}
@Nullable
@Override
public Uri insert(@NonNull Uri uri, @Nullable ContentValues contentValues) {
SQLiteDatabase db=dbhelper.getReadableDatabase();//获取数据库
Uri urireturn=null;
switch (uriMatcher.match(uri)){
case BOOK_DIR:
case BOOk_ITEM:
long newBoookId=db.insert("Book",null,contentValues);//插入第几行
urireturn=Uri.parse("content://"+AUTHORITY+"/Book/"+newBoookId);
break;
}
return urireturn;
}
@Override
public int delete(@NonNull Uri uri, @Nullable String s, @Nullable String[] strings) {
SQLiteDatabase db=dbhelper.getReadableDatabase();
int deletedRows=0;
switch (uriMatcher.match(uri)){
case BOOK_DIR:
deletedRows=db.delete("Book",s,strings);
break;
case BOOk_ITEM:
String id=uri.getPathSegments().get(1);
deletedRows=db.delete("Book","id=?",new String[]{id});
break;
}
return deletedRows;
}
@Override
public int update(@NonNull Uri uri, @Nullable ContentValues contentValues, @Nullable String s, @Nullable String[] strings) {
SQLiteDatabase db=dbhelper.getReadableDatabase();
int updateRows=0;
switch (uriMatcher.match(uri)){
case BOOK_DIR:
updateRows=db.update("Book",contentValues,s,strings);
break;
case BOOk_ITEM:
String id=uri.getPathSegments().get(1);
updateRows=db.update("Book",contentValues,"id=?",new String[]{id});
break;
}
return updateRows;
}
@Nullable
@Override
public String getType(@NonNull Uri uri) {
switch (uriMatcher.match(uri)){
case BOOK_DIR:
return "vnd.android.cursor.dir/vnd.text.sqlitedatabase.provider.Book";
case BOOk_ITEM:
return "vnd.android.cursor.item/vnd.text.sqlitedatabase.provider.Book";
}
return null;
}
}
网友评论