Android 数据存储之ContentProvider 使用和应用场景
备注:
ContentProvider1进程一代码:https://github.com/zengyuan/ContentProvider1Mode
ContentProvider1进程二代码:https://github.com/zengyuan/ContentProvider2Mode
Android Service 启动方式,生命周期和应用场景详解: https://www.cnblogs.com/finn21/p/11652482.html
iOS APP打包上传审核和 客服咨询流程(审核被拒,账号问题等):https://www.cnblogs.com/finn21/p/11084272.html
注意,最主要是provider的配置,以及URl的provider地址要相同;
一,ContentProvider 主要用于不同的应用程序之间实现数据共享功能!
主要分为6个:
1.使用SQLite技术,创建好数据库和数据表;
2.新建类继承ContentProvider,重写6个抽象方法(通过这六个方法对数据库进行操作);
3.在Manifest中注册provider;
4.创建UriMatcher,定义Uri规则,添加注册数据库链表的名称;
5.ContentResolver对ContentProvider中共享的数据进行增删改查操作;
6.获取数据并修改等(进程一进程二增删改查方式一样);
二,进程一代码伺候:
第一步创建数据库(sql语句直接执行的):
package com.saiyi.contentproviderdemo1; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; /** * <pre> * author : Finn * e-mail : 892603597@qq.com * time : 2019/10/14 * desc : https://www.cnblogs.com/finn21/ * </pre> */ public class DBHelper extends SQLiteOpenHelper { // 数据库名 private static final String DATABASE_NAME = "Finn.db"; // 链表名称 public static final String USER_TABLE_NAME = "user"; public static final String JOB_TABLE_NAME = "job"; private static final int DATABASE_VERSION = 1; //数据库版本号 public DBHelper(Context context) { super(context,DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { // 创建两个表格:用户表 和职业表 db.execSQL("CREATE TABLE IF NOT EXISTS " + USER_TABLE_NAME + "(_id INTEGER PRIMARY KEY AUTOINCREMENT," + " name TEXT)"); db.execSQL("CREATE TABLE IF NOT EXISTS " + JOB_TABLE_NAME + "(_id INTEGER PRIMARY KEY AUTOINCREMENT," + " job TEXT)"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } @Override public void onOpen(SQLiteDatabase db) { super.onOpen(db); } @Override public synchronized void close() { super.close(); } }
第一步创建数据库(通过自行封装之后的数据库):
package com.saiyi.contentproviderdemo1; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; /** * <pre> * author : Finn * e-mail : 892603597@qq.com * time : 2019/10/14 * desc : https://www.cnblogs.com/finn21/ * </pre> */ public class MyDataBaseHelper extends SQLiteOpenHelper { private static final String DATABASE_NAME = "KfbFinnSS.db"; private static final int DATABASE_VERSION = 1; public static final String USER_ID = "userid_id";// 自动增长表id /***.用户名(存储车型af)**/ public static final String TABLE_USER_AF = "table_user_af"; public static final String USER_USER_AF = "car_user_name_af";//用户名 public static final String USER_CAR_AZ_AF = "car_user_az_af";//字符分段 public static final String USER_CAR_NAME_AF = "car_kfb_name_af";// 车名称 public static final String USER_CAR_TYPE_AF = "car_user_cartype_af";// 车型号 public static final String USER_CAR_DATE_AF = "car_kfb_date_af";// 年份 public static final String USER_CAR_LENGM_AF = "car_kfb_lengmei_af";// 冷媒量 public MyDataBaseHelper(Context context) { super(context,DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { /** AF * */ db.execSQL("CREATE TABLE " + TABLE_USER_AF + " (" + USER_ID + " INTEGER PRIMARY KEY," + USER_USER_AF + " INTEGER NOT NUll," + USER_CAR_AZ_AF + " TEXT," + USER_CAR_NAME_AF + " TEXT," + USER_CAR_TYPE_AF + " TEXT," + USER_CAR_DATE_AF + " TEXT NOT NUll," + USER_CAR_LENGM_AF + " INTEGER default 0);"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { //数据库升级启动该方法 } @Override public synchronized void close() { super.close(); } @Override public void onOpen(SQLiteDatabase db) { super.onOpen(db); } }
package com.saiyi.contentproviderdemo1; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import java.util.ArrayList; import java.util.List; /** * <pre> * author : Finn * e-mail : 892603597@qq.com * time : 2019/10/14 * desc : https://www.cnblogs.com/finn21/ * </pre> */ public class MyDataBase { private static final String TAG = MyDataBase.class.getSimpleName(); private static MyDataBaseHelper databaseHelper; private static MyDataBase myDisplacementBase; private static String USER_NAME = "13006602877"; private static String TABLE_USER_NAME = "KFB"; private MyDataBase(Context context) { databaseHelper = new MyDataBaseHelper(context); } public static MyDataBase getInstance(Context context) { if (myDisplacementBase == null) { myDisplacementBase = new MyDataBase(context.getApplicationContext()); } return myDisplacementBase; } /** * 关闭当前的db * * @param db */ synchronized void closeSQLDB(SQLiteDatabase db) { SQLiteDatabase.releaseMemory(); if (db != null && db.isOpen()) { db.close(); db = null; } } /** * 通知本地数据库有变化 */ public interface InotifyDBhasChange { int CODE_ERR_REPET = 0; void onChange(Object... obj); void err(int... code); } /** * --------------------------------------添加车名AF--------------------------------------- */ public synchronized void InsertCarAF(CarInfo info) { SQLiteDatabase writeDB = databaseHelper.getWritableDatabase(); Cursor cursor = writeDB.query(MyDataBaseHelper.TABLE_USER_AF, new String[]{MyDataBaseHelper.USER_ID}, MyDataBaseHelper.USER_USER_AF + " = ? ", new String[]{TABLE_USER_NAME}, null, null, null); cursor.close(); ContentValues cv = new ContentValues(); cv.put(MyDataBaseHelper.USER_USER_AF, TABLE_USER_NAME); cv.put(MyDataBaseHelper.USER_CAR_AZ_AF, info.getAz()); cv.put(MyDataBaseHelper.USER_CAR_NAME_AF, info.getCarName()); cv.put(MyDataBaseHelper.USER_CAR_TYPE_AF, info.getCarType()); cv.put(MyDataBaseHelper.USER_CAR_DATE_AF, info.getCarDate()); cv.put(MyDataBaseHelper.USER_CAR_LENGM_AF, info.getCarLengM()); try { writeDB.insert(MyDataBaseHelper.TABLE_USER_AF, null, cv);//插入数据 } catch (Exception e) { return; } finally { closeSQLDB(writeDB); } } /** * 查询所有用户 */ public synchronized List<CarInfo> QueryListAF() { List<CarInfo> list = new ArrayList<>(); SQLiteDatabase readDB = databaseHelper.getReadableDatabase(); Cursor cursor = readDB.query(MyDataBaseHelper.TABLE_USER_AF, null, MyDataBaseHelper.USER_USER_AF + " = ? ", new String[]{TABLE_USER_NAME}, null, null, MyDataBaseHelper.USER_ID, null); try { // int user = cursor.getColumnIndex(MyDataBaseHelper.USER_USER_AF); int pswd = cursor.getColumnIndex(MyDataBaseHelper.USER_CAR_AZ_AF); int icon = cursor.getColumnIndex(MyDataBaseHelper.USER_CAR_NAME_AF); int nickname = cursor.getColumnIndex(MyDataBaseHelper.USER_CAR_TYPE_AF); int vertion = cursor.getColumnIndex(MyDataBaseHelper.USER_CAR_DATE_AF); int veron = cursor.getColumnIndex(MyDataBaseHelper.USER_CAR_LENGM_AF); while (cursor.moveToNext()) { CarInfo info = new CarInfo( cursor.getString(pswd), cursor.getString(icon), cursor.getString(nickname), cursor.getString(vertion), cursor.getString(veron) ); list.add(info); } } catch (Exception e) { } finally { if (cursor != null) { cursor.close(); } closeSQLDB(readDB); } return list; } public Cursor cursor; public SQLiteDatabase readDB; public synchronized Cursor QueryCursor() { readDB = databaseHelper.getReadableDatabase(); cursor = readDB.query(MyDataBaseHelper.TABLE_USER_AF, null, MyDataBaseHelper.USER_USER_AF + " = ? ", new String[]{TABLE_USER_NAME}, null, null, MyDataBaseHelper.USER_ID, null); return cursor; } public synchronized void CloseCursor() { if (cursor != null) { cursor.close(); } closeSQLDB(readDB); } /** * 查询所有用户 */ public synchronized Cursor QueryListAFA() { SQLiteDatabase readDB = databaseHelper.getReadableDatabase(); Cursor cursor = readDB.query(MyDataBaseHelper.TABLE_USER_AF, null, MyDataBaseHelper.USER_USER_AF + " = ? ", new String[]{TABLE_USER_NAME}, null, null, MyDataBaseHelper.USER_ID, null); try { } catch (Exception e) { } finally { if (cursor != null) { cursor.close(); } closeSQLDB(readDB); } return cursor; } /** * 查询AF特定名称的车类型 */ public synchronized List<CarInfo> QueryListAFCarName(String Carname) { List<CarInfo> list = new ArrayList<>(); SQLiteDatabase readDB = databaseHelper.getReadableDatabase(); Cursor cursor = readDB.query(MyDataBaseHelper.TABLE_USER_AF, null, MyDataBaseHelper.USER_USER_AF + " = ? and " + MyDataBaseHelper.USER_CAR_NAME_AF + " = ? ", new String[]{TABLE_USER_NAME, Carname}, null, null, MyDataBaseHelper.USER_ID, null); try { // int user = cursor.getColumnIndex(MyDataBaseHelper.USER_USER_AF); int pswd = cursor.getColumnIndex(MyDataBaseHelper.USER_CAR_AZ_AF); int icon = cursor.getColumnIndex(MyDataBaseHelper.USER_CAR_NAME_AF); int nickname = cursor.getColumnIndex(MyDataBaseHelper.USER_CAR_TYPE_AF); int vertion = cursor.getColumnIndex(MyDataBaseHelper.USER_CAR_DATE_AF); int veron = cursor.getColumnIndex(MyDataBaseHelper.USER_CAR_LENGM_AF); while (cursor.moveToNext()) { CarInfo info = new CarInfo( cursor.getString(pswd), cursor.getString(icon), cursor.getString(nickname), cursor.getString(vertion), cursor.getString(veron) ); list.add(info); } } catch (Exception e) { } finally { if (cursor != null) { cursor.close(); } closeSQLDB(readDB); } return list; } /** * 查询AF特定名称和车类型 的生产年份 */ public synchronized List<CarInfo> QueryListAFCarNameYeas(String Carname,String CarType) { List<CarInfo> list = new ArrayList<>(); SQLiteDatabase readDB = databaseHelper.getReadableDatabase(); Cursor cursor = readDB.query(MyDataBaseHelper.TABLE_USER_AF, null, MyDataBaseHelper.USER_USER_AF + " = ? and " + MyDataBaseHelper.USER_CAR_NAME_AF + " = ? and " + MyDataBaseHelper.USER_CAR_TYPE_AF + " = ? ", new String[]{TABLE_USER_NAME, Carname,CarType}, null, null, MyDataBaseHelper.USER_ID, null); try { // int user = cursor.getColumnIndex(MyDataBaseHelper.USER_USER_AF); int pswd = cursor.getColumnIndex(MyDataBaseHelper.USER_CAR_AZ_AF); int icon = cursor.getColumnIndex(MyDataBaseHelper.USER_CAR_NAME_AF); int nickname = cursor.getColumnIndex(MyDataBaseHelper.USER_CAR_TYPE_AF); int vertion = cursor.getColumnIndex(MyDataBaseHelper.USER_CAR_DATE_AF); int veron = cursor.getColumnIndex(MyDataBaseHelper.USER_CAR_LENGM_AF); while (cursor.moveToNext()) { CarInfo info = new CarInfo( cursor.getString(pswd), cursor.getString(icon), cursor.getString(nickname), cursor.getString(vertion), cursor.getString(veron) ); list.add(info); } } catch (Exception e) { } finally { if (cursor != null) { cursor.close(); } closeSQLDB(readDB); } return list; } /** * 删除列表数据 */ public synchronized void DeletInfoAF(InotifyDBhasChange dbChange) { SQLiteDatabase writeDB = databaseHelper.getWritableDatabase(); try { writeDB.delete( MyDataBaseHelper.TABLE_USER_AF, MyDataBaseHelper.USER_USER_AF + " = ? " , new String[]{TABLE_USER_NAME}); } catch (Exception e) { dbChange.err(); return; } finally { closeSQLDB(writeDB); } dbChange.onChange(); } }
第二步:2.新建类继承ContentProvider,重写6个抽象方法
package com.saiyi.contentproviderdemo1; import android.content.ContentProvider; import android.content.ContentValues; import android.content.Context; import android.content.UriMatcher; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.net.Uri; import android.util.Log; /** * <pre> * author : Finn * e-mail : 892603597@qq.com * time : 2019/10/14 * desc : https://www.cnblogs.com/finn21/ * </pre> */ public class BaseContentProvider extends ContentProvider{ private Context mContext; DBHelper mDbHelper = null; SQLiteDatabase db = null; public static final String AUTOHORITY = "Finn.zy.myprovider"; // 设置ContentProvider的唯一标识 public static final int User_Code = 1; public static final int Job_Code = 2; public static final int AF_Code = 32; // UriMatcher类使用:在ContentProvider 中注册URI private static final UriMatcher mMatcher; public static DataBaseMonitor mListener = null; public static void setDataBaseMonitorListener(DataBaseMonitor listener) { mListener = listener; } static{ mMatcher = new UriMatcher(UriMatcher.NO_MATCH); // 初始化 mMatcher.addURI(AUTOHORITY,DBHelper.USER_TABLE_NAME, User_Code); // 若URI资源路径 = "content://" + AUTOHORITY +"/user" mMatcher.addURI(AUTOHORITY, DBHelper.JOB_TABLE_NAME, Job_Code);// 若URI资源路径 = "content://" + AUTOHORITY +"/job" mMatcher.addURI(AUTOHORITY, MyDataBaseHelper.TABLE_USER_AF, AF_Code);// 若URI资源路径 = "content://" + AUTOHORITY +"/job" // 固定前缀 "content://" + AUTOHORITY,数据库链表的名称,则返回注册码User_Code //固定前缀 "content://" + AUTOHORITY ,数据库链表的名称,则返回注册码Job_Code } // 以下是ContentProvider的6个方法 @Override public boolean onCreate() { //该方法在ContentProvider创建后就会被调用,Android开机后, // ContentProvider在其它应用第一次访问它时才会被创建,同时,要讲返回值修改成true。 mContext = getContext(); // 在ContentProvider创建时对数据库进行初始化 // 运行在主线程,故不能做耗时操作,此处仅作展示 mDbHelper = new DBHelper(getContext()); db = mDbHelper.getWritableDatabase(); // 初始化两个表的数据(先清空两个表,再各加入一个记录) db.execSQL("delete from user"); db.execSQL("insert into user values(1,'Carson');"); db.execSQL("insert into user values(2,'Kobe');"); MyDataBase.getInstance(mContext).InsertCarAF(new CarInfo("宝马","奔驰","路虎","宾利","保时捷")); MyDataBase.getInstance(mContext).InsertCarAF(new CarInfo("宝马1","奔驰2","路虎3","宾利4","保时捷5")); return true; } public static final int ITEMS = 1; public static final int ITEMS_ID = 2; // 如果操作的数据属于集合类型,那么MIME类型字符串应该以vnd.android.cursor.dir/开头。 // 例如:要得到所有person记录的Uri为content://com.cfox.contentprovid.PersonProvider/person // 那么返回的MIME类型字符串应该为:"vnd.android.cursor.dir/person" // 如果要操作的数据属于非集合类型数据,那么MIME类型字符串应该以vnd.android.cursor.item/开头 // 例如:得到id为10的person记录,Uri为content://com.cfox.contentprovid.PersonProvider/person/10 // 那么返回的MIME类型字符串为:"vnd.android.cursor.item/person" @Override public String getType(Uri uri) { return null; } @Override public Uri insert(Uri uri, ContentValues values) { //该方法用于供外部应用往ContentProvider添加数据。 // 根据URI匹配 URI_CODE,从而匹配ContentProvider中相应的表名 // 该方法在最下面 String table = getTableName(uri); Log.e("sdfsdf",table+"====="+MyDataBaseHelper.TABLE_USER_AF); if(table != null && !MyDataBaseHelper.TABLE_USER_AF.equals(table)){ // 向该表添加数据 db.insert(table, null, values); // 当该URI的ContentProvider数据发生变化时,通知外界(即访问该ContentProvider数据的访问者) mContext.getContentResolver().notifyChange(uri, null); return uri; }else{ FinnInsert(uri,values); return uri; } // // 通过ContentUris类从URL中获取ID // long personid = ContentUris.parseId(uri); // System.out.println(personid); } @Override public int delete(Uri uri, String selection, String[] selectionArgs) { //该方法用于供外部应用从ContentProvider删除数据。 String tableName = getTableName(uri); if(!MyDataBaseHelper.TABLE_USER_AF.equals(tableName)){ //使用原生函数的数据库 return 0; }else{ //使用封装之后的数据库 return 0; } } @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { return 0; } /** * 查询数据 */ @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { //该方法用于供外部应用从ContentProvider中获取数据。 // 根据URI匹配 URI_CODE,从而匹配ContentProvider中相应的表名 // 该方法在最下面 String tableName = getTableName(uri); FinnQuery(tableName); // // 通过ContentUris类从URL中获取ID // long personid = ContentUris.parseId(uri); // System.out.println(personid); // 查询数据+ if(!MyDataBaseHelper.TABLE_USER_AF.equals(tableName)){ //使用原生函数的数据库 return db.query(tableName,projection,selection,selectionArgs,null,null,sortOrder,null); }else{ //使用封装之后的数据库 return MyDataBase.getInstance(mContext).QueryCursor(); } } /** * 根据URI匹配 URI_CODE,从而匹配ContentProvider中相应的表名 */ public static final String getTableName(Uri uri){ String tableName = null; switch (mMatcher.match(uri)) { case User_Code: tableName = DBHelper.USER_TABLE_NAME; break; case Job_Code: tableName = DBHelper.JOB_TABLE_NAME; break; case AF_Code: tableName = MyDataBaseHelper.TABLE_USER_AF; break; } return tableName; } public void FinnInsert(Uri uri, ContentValues values) { //自行封装方法添加数据库 String table = getTableName(uri); switch (table){//根据表名 插入数据 case MyDataBaseHelper.TABLE_USER_AF://通过KEY获取value MyDataBase.getInstance(mContext).InsertCarAF(new CarInfo( values.get("car_user_az_af").toString(), values.get("car_kfb_name_af").toString(), values.get("car_user_cartype_af").toString(), values.get("car_kfb_date_af").toString(), values.get("car_kfb_lengmei_af").toString() )); // MyDataBase.getInstance(mContext).InsertCarAF(new CarInfo( // values.get(MyDataBaseHelper.USER_CAR_AZ_AF).toString(), values.get(MyDataBaseHelper.USER_CAR_NAME_AF).toString(), // values.get(MyDataBaseHelper.USER_CAR_TYPE_AF).toString(), values.get(MyDataBaseHelper.USER_CAR_DATE_AF).toString(), // values.get(MyDataBaseHelper.USER_CAR_LENGM_AF).toString() // )); break; default: break; } } public void FinnQuery(String tablename) { //自行封装方法添加数据库 switch (tablename){//根据表名 插入数据 case MyDataBaseHelper.TABLE_USER_AF: mListener.OnRelist(MyDataBase.getInstance(mContext).QueryListAF()); break; default: break; } } }
第三步:在Manifest中注册provider;
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" package="com.saiyi.contentproviderdemo1"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme" tools:ignore="GoogleAppIndexingWarning"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <!--authorities地址和 BaseContentProvider中的AUTOHORITY要保持一致--> <provider android:name=".BaseContentProvider" android:authorities="Finn.zy.myprovider" android:enabled="true" android:exported="true" /> </application> </manifest>
package com.saiyi.contentproviderdemo1;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.util.Log;
/**
* <pre>
* author : Finn
* e-mail : 892603597@qq.com
* time : 2019/10/14
* desc : https://www.cnblogs.com/finn21/
* </pre>
*/
public class BaseContentProvider extends ContentProvider{
private Context mContext;
DBHelper mDbHelper = null;
SQLiteDatabase db = null;
public static final String AUTOHORITY = "Finn.zy.myprovider";
// 设置ContentProvider的唯一标识
public static final int User_Code = 1;
public static final int Job_Code = 2;
public static final int AF_Code = 32;
// UriMatcher类使用:在ContentProvider 中注册URI
private static final UriMatcher mMatcher;
public static DataBaseMonitor mListener = null;
public static void setDataBaseMonitorListener(DataBaseMonitor listener) {
mListener = listener;
}
static{
mMatcher = new UriMatcher(UriMatcher.NO_MATCH);
// 初始化
mMatcher.addURI(AUTOHORITY,DBHelper.USER_TABLE_NAME, User_Code); // 若URI资源路径 = "content://" + AUTOHORITY +"/user"
mMatcher.addURI(AUTOHORITY, DBHelper.JOB_TABLE_NAME, Job_Code);// 若URI资源路径 = "content://" + AUTOHORITY +"/job"
mMatcher.addURI(AUTOHORITY, MyDataBaseHelper.TABLE_USER_AF, AF_Code);// 若URI资源路径 = "content://" + AUTOHORITY +"/job"
// 固定前缀 "content://" + AUTOHORITY,数据库链表的名称,则返回注册码User_Code
//固定前缀 "content://" + AUTOHORITY ,数据库链表的名称,则返回注册码Job_Code
}
// 以下是ContentProvider的6个方法
@Override
public boolean onCreate() {
//该方法在ContentProvider创建后就会被调用,Android开机后,
// ContentProvider在其它应用第一次访问它时才会被创建,同时,要讲返回值修改成true。
mContext = getContext();
// 在ContentProvider创建时对数据库进行初始化
// 运行在主线程,故不能做耗时操作,此处仅作展示
mDbHelper = new DBHelper(getContext());
db = mDbHelper.getWritableDatabase();
// 初始化两个表的数据(先清空两个表,再各加入一个记录)
db.execSQL("delete from user");
db.execSQL("insert into user values(1,'Carson');");
db.execSQL("insert into user values(2,'Kobe');");
MyDataBase.getInstance(mContext).InsertCarAF(new CarInfo("宝马","奔驰","路虎","宾利","保时捷"));
MyDataBase.getInstance(mContext).InsertCarAF(new CarInfo("宝马1","奔驰2","路虎3","宾利4","保时捷5"));
return true;
}
public static final int ITEMS = 1;
public static final int ITEMS_ID = 2;
// 如果操作的数据属于集合类型,那么MIME类型字符串应该以vnd.android.cursor.dir/开头。
// 例如:要得到所有person记录的Uri为content://com.cfox.contentprovid.PersonProvider/person
// 那么返回的MIME类型字符串应该为:"vnd.android.cursor.dir/person"
// 如果要操作的数据属于非集合类型数据,那么MIME类型字符串应该以vnd.android.cursor.item/开头
// 例如:得到id为10的person记录,Uri为content://com.cfox.contentprovid.PersonProvider/person/10
// 那么返回的MIME类型字符串为:"vnd.android.cursor.item/person"
@Override
public String getType(Uri uri) {
return null;
}
@Override
public Uri insert(Uri uri, ContentValues values) {
//该方法用于供外部应用往ContentProvider添加数据。
// 根据URI匹配 URI_CODE,从而匹配ContentProvider中相应的表名
// 该方法在最下面
String table = getTableName(uri);
Log.e("sdfsdf",table+"====="+MyDataBaseHelper.TABLE_USER_AF);
if(table != null && !MyDataBaseHelper.TABLE_USER_AF.equals(table)){
// 向该表添加数据
db.insert(table, null, values);
// 当该URI的ContentProvider数据发生变化时,通知外界(即访问该ContentProvider数据的访问者)
mContext.getContentResolver().notifyChange(uri, null);
return uri;
}else{
FinnInsert(uri,values);
return uri;
}
// // 通过ContentUris类从URL中获取ID
// long personid = ContentUris.parseId(uri);
// System.out.println(personid);
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
//该方法用于供外部应用从ContentProvider删除数据。
String tableName = getTableName(uri);
if(!MyDataBaseHelper.TABLE_USER_AF.equals(tableName)){
//使用原生函数的数据库
return 0;
}else{
//使用封装之后的数据库
return 0;
}
}
@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
return 0;
}
/**
* 查询数据
*/
@Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
//该方法用于供外部应用从ContentProvider中获取数据。
// 根据URI匹配 URI_CODE,从而匹配ContentProvider中相应的表名
// 该方法在最下面
String tableName = getTableName(uri);
FinnQuery(tableName);
// // 通过ContentUris类从URL中获取ID
// long personid = ContentUris.parseId(uri);
// System.out.println(personid);
// 查询数据+
if(!MyDataBaseHelper.TABLE_USER_AF.equals(tableName)){
//使用原生函数的数据库
return db.query(tableName,projection,selection,selectionArgs,null,null,sortOrder,null);
}else{
//使用封装之后的数据库
return MyDataBase.getInstance(mContext).QueryCursor();
}
}
/**
* 根据URI匹配 URI_CODE,从而匹配ContentProvider中相应的表名
*/
public static final String getTableName(Uri uri){
String tableName = null;
switch (mMatcher.match(uri)) {
case User_Code:
tableName = DBHelper.USER_TABLE_NAME;
break;
case Job_Code:
tableName = DBHelper.JOB_TABLE_NAME;
break;
case AF_Code:
tableName = MyDataBaseHelper.TABLE_USER_AF;
break;
}
return tableName;
}
public void FinnInsert(Uri uri, ContentValues values) {
//自行封装方法添加数据库
String table = getTableName(uri);
switch (table){//根据表名 插入数据
case MyDataBaseHelper.TABLE_USER_AF://通过KEY获取value
MyDataBase.getInstance(mContext).InsertCarAF(new CarInfo(
values.get("car_user_az_af").toString(), values.get("car_kfb_name_af").toString(),
values.get("car_user_cartype_af").toString(), values.get("car_kfb_date_af").toString(),
values.get("car_kfb_lengmei_af").toString()
));
// MyDataBase.getInstance(mContext).InsertCarAF(new CarInfo(
// values.get(MyDataBaseHelper.USER_CAR_AZ_AF).toString(), values.get(MyDataBaseHelper.USER_CAR_NAME_AF).toString(),
// values.get(MyDataBaseHelper.USER_CAR_TYPE_AF).toString(), values.get(MyDataBaseHelper.USER_CAR_DATE_AF).toString(),
// values.get(MyDataBaseHelper.USER_CAR_LENGM_AF).toString()
// ));
break;
default:
break;
}
}
public void FinnQuery(String tablename) {
//自行封装方法添加数据库
switch (tablename){//根据表名 插入数据
case MyDataBaseHelper.TABLE_USER_AF:
mListener.OnRelist(MyDataBase.getInstance(mContext).QueryListAF());
break;
default:
break;
}
}
}