一、初略介紹
ContentProvider叛薯,即內容提供者浑吟,是 Android 四大組件之一笙纤。主要功能是進程間數(shù)據(jù)交互/共享。詳細內容請看這篇文章:Android:關于ContentProvider的知識都在這里了组力!
二粪糙、代碼實現(xiàn)
1、首先要在一個應用中注冊ContentProvider組件
/**
* 定義一個保存contentprovider數(shù)據(jù)的數(shù)據(jù)庫
*/
public class WhhConfigDB extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "whhconfig.db";
private static final int DATABASE_VERSION = 1;
public WhhConfigDB(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String sql = "CREATE TABLE IF NOT EXISTS " + WhhConfigConstant.TABLE_NAME + "(" +
WhhConfigConstant._ID + " integer primary key autoincrement," +
WhhConfigConstant.KEY + " text," +
WhhConfigConstant.VALUE + " text" +
")";
db.execSQL(sql);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.d("whh", "WhhConfigDB onUpgrade");
}
}
/**
* 定義一個ContentProvider,記得在AndroidManifest.xml中靜態(tài)注冊
*/
public class WhhConfigProvider extends ContentProvider {
private WhhConfigDB sharedDB;
private static final UriMatcher MATCHER;
private static final int SHARES = 1;
// private static final int SHARE = 2;
static {
MATCHER = new UriMatcher(UriMatcher.NO_MATCH);
MATCHER.addURI(WhhConfigConstant.AUTHORITY, WhhConfigConstant.TABLE_NAME, SHARES);
// MATCHER.addURI("com.evideo.kmbox.kmshareprovider", "kmshare/#", SHARE);
}
@Override
public boolean onCreate() {
EvLog.d("WhhConfigProvider onCreate...");
//在這創(chuàng)建數(shù)據(jù)庫
this.sharedDB = new WhhConfigDB(this.getContext());
return false;
}
@Override
public Cursor query(@NonNull Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
SQLiteDatabase db = sharedDB.getReadableDatabase();
if (db == null) {
return null;
}
switch (MATCHER.match(uri)) {
case SHARES:
return db.query(WhhConfigConstant.TABLE_NAME, projection, selection, selectionArgs,
null, null, sortOrder);
// case SHARE:
// long id = ContentUris.parseId(uri);
// String where = "_id=" + id;
// if (selection != null && !"".equals(selection)) {
// where = selection + " and " + where;
// }
// return db.query("kmshare", projection, where, selectionArgs, null,
// null, sortOrder);
default:
throw new IllegalArgumentException("Unkwon Uri:" + uri.toString());
}
}
//返回數(shù)據(jù)的MIME類型忿项。
@Override
public String getType(@NonNull Uri uri) {
switch (MATCHER.match(uri)) {
case SHARES:
return WhhConfigConstant.DIR_TYPE;
// case SHARE:
// return "vnd.android.cursor.item/kmshare";
default:
throw new IllegalArgumentException("Unkwon Uri:" + uri.toString());
}
}
@Override
public Uri insert(@NonNull Uri uri, ContentValues values) {
SQLiteDatabase db = sharedDB.getWritableDatabase();
if (db == null) {
return null;
}
switch (MATCHER.match(uri)) {
case SHARES:
// 第二個參數(shù)是當key字段為空時,將自動插入一個NULL城舞。
long rowid = db.insert(WhhConfigConstant.TABLE_NAME, WhhConfigConstant.KEY, values);
Uri insertUri = ContentUris.withAppendedId(uri, rowid);
// this.getContext().getContentResolver().notifyChange(uri, null);
ContentResolver cr = this.getContext().getContentResolver();
if (cr != null) {
cr.notifyChange(Uri.withAppendedPath(uri, values.getAsString(WhhConfigConstant.KEY)), null);
}
return insertUri;
default:
throw new IllegalArgumentException("Unkwon Uri:" + uri.toString());
}
}
@Override
public int delete(@NonNull Uri uri, String selection, String[] selectionArgs) {
SQLiteDatabase db = sharedDB.getWritableDatabase();
if (db == null) {
return 0;
}
int count = 0;
switch (MATCHER.match(uri)) {
case SHARES:
count = db.delete(WhhConfigConstant.TABLE_NAME, selection, selectionArgs);
return count;
// case SHARE:
// long id = ContentUris.parseId(uri);
// String where = "_id=" + id;
// if (selection != null && !"".equals(selection)) {
// where = selection + " and " + where;
// }
// count = db.delete("kmshare", where, selectionArgs);
// return count;
default:
throw new IllegalArgumentException("Unkwon Uri:" + uri.toString());
}
}
@Override
public int update(@NonNull Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
SQLiteDatabase db = sharedDB.getWritableDatabase();
if (db == null) {
return 0;
}
int count = 0;
switch (MATCHER.match(uri)) {
case SHARES:
count = db.update(WhhConfigConstant.TABLE_NAME, values, selection, selectionArgs);
ContentResolver cr = this.getContext().getContentResolver();
if (cr != null) {
cr.notifyChange(Uri.withAppendedPath(uri, values.getAsString(WhhConfigConstant.KEY)), null);
}
return count;
// case SHARE:
// long id = ContentUris.parseId(uri);
// String where = "_id=" + id;
// if (selection != null && !"".equals(selection)) {
// where = selection + " and " + where;
// }
// count = db.update("kmshare", values, where, selectionArgs);
// return count;
default:
throw new IllegalArgumentException("Unkwon Uri:" + uri.toString());
}
}
}
//注意在AndroidManifest.xml中靜態(tài)注冊一下ContentProvider
<provider
android:name=".provider.WhhConfigProvider"
android:authorities="com.whh.shareprovider"
android:exported="true" />
/**
* 數(shù)據(jù)庫常量類
*/
public class KmConfigConstant {
public static final String AUTHORITY = "com.evideo.kmbox.kmshareprovider";
public static final String TABLE_NAME = "tblWhhconfig";
public static final String DIR_TYPE = "vnd.android.cursor.dir/tblKmconfig";
public static final String KEY = "key";
public static final String VALUE = "value";
public static final String _ID = "_id";
public static final String SCHEME = "content://";
public static final String URI = "content://com.whh.shareprovider/tblWhhconfig";
public static final String SELECTION = "key=?";
}
三轩触、封裝調用
public class WhhConfigManager {
private Uri selectUri;
private Context mContext;
private WhhConfigManager() {
this.selectUri = Uri.parse("content://com.whh.shareprovider/tblWhhconfig");
this.mContext = ApplicationUtil.getInstance();
}
public static WhhConfigManager getInstance() {
return WhhConfigManager.LazyHold.sInstance;
}
public boolean putBoolean(String key, boolean value) {
String bValue = String.valueOf(value);
return this.put(key, bValue);
}
public boolean putString(String key, String value) {
return this.put(key, value);
}
public boolean putInt(String key, int value) {
String iValue = String.valueOf(value);
return this.put(key, iValue);
}
public boolean putLong(String key, long value) {
String lValue = String.valueOf(value);
return this.put(key, lValue);
}
public boolean putFloat(String key, float value) {
String fValue = String.valueOf(value);
return this.put(key, fValue);
}
private boolean put(String key, String value) {
if (TextUtils.isEmpty(key)) {
return false;
} else {
ContentResolver cr = this.mContext.getContentResolver();
ContentValues cv = new ContentValues();
cv.put("key", key);
cv.put("value", value);
if (!this.contains(key)) {
cr.insert(this.selectUri, cv);
} else {
cr.update(this.selectUri, cv, "key=?", new String[]{key});
}
cr.notifyChange(this.selectUri, (ContentObserver)null);
return true;
}
}
public boolean getBoolean(String key, boolean def) {
if (TextUtils.isEmpty(key)) {
return def;
} else {
ContentResolver cr = this.mContext.getContentResolver();
Cursor c = cr.query(this.selectUri, (String[])null, "key=?", new String[]{key}, (String)null);
if (c == null) {
return def;
} else if (!c.moveToFirst()) {
c.close();
return def;
} else {
int col = c.getColumnIndex("value");
String value = c.getString(col);
c.close();
return Boolean.valueOf(value);
}
}
}
public String getString(String key, String def) {
ContentResolver cr = this.mContext.getContentResolver();
Cursor c = cr.query(this.selectUri, (String[])null, "key=?", new String[]{key}, (String)null);
if (c == null) {
return def;
} else if (!c.moveToFirst()) {
c.close();
return def;
} else {
int col = c.getColumnIndex("value");
String value = c.getString(col);
c.close();
return value;
}
}
public int getInt(String key, int def) {
ContentResolver cr = this.mContext.getContentResolver();
Cursor c = cr.query(this.selectUri, (String[])null, "key=?", new String[]{key}, (String)null);
if (c == null) {
return def;
} else if (!c.moveToFirst()) {
c.close();
return def;
} else {
int col = c.getColumnIndex("value");
String value = c.getString(col);
c.close();
return Integer.valueOf(value);
}
}
public float getFloat(String key, float def) {
ContentResolver cr = this.mContext.getContentResolver();
Cursor c = cr.query(this.selectUri, (String[])null, "key=?", new String[]{key}, (String)null);
if (c == null) {
return def;
} else if (!c.moveToFirst()) {
c.close();
return def;
} else {
int col = c.getColumnIndex("value");
String value = c.getString(col);
c.close();
return Float.valueOf(value);
}
}
public Long getLong(String key, long def) {
ContentResolver cr = this.mContext.getContentResolver();
Cursor c = cr.query(this.selectUri, (String[])null, "key=?", new String[]{key}, (String)null);
if (c == null) {
return def;
} else if (!c.moveToFirst()) {
c.close();
return def;
} else {
int col = c.getColumnIndex("value");
String value = c.getString(col);
c.close();
return Long.valueOf(value);
}
}
public boolean contains(String key) {
ContentResolver cr = this.mContext.getContentResolver();
Cursor c = cr.query(this.selectUri, (String[])null, "key=?", new String[]{key}, (String)null);
if (c == null) {
return false;
} else if (!c.moveToFirst()) {
c.close();
return false;
} else {
c.close();
return true;
}
}
public boolean remove(String key) {
ContentResolver cr = this.mContext.getContentResolver();
int result = cr.delete(this.selectUri, "key=?", new String[]{key});
return result != -1;
}
public Map<String, String> getAllInfo() {
Map<String, String> contentInfo = new HashMap();
ContentResolver cr = this.mContext.getContentResolver();
Cursor c = cr.query(this.selectUri, (String[])null, (String)null, (String[])null, (String)null);
if (c == null) {
return contentInfo;
} else {
while(c.moveToNext()) {
int colKey = c.getColumnIndex("key");
int colValue = c.getColumnIndex("value");
contentInfo.put(c.getString(colKey), c.getString(colValue));
}
c.close();
return contentInfo;
}
}
public void registerContentObserver(ContentObserver observer) {
if (observer != null) {
this.mContext.getContentResolver().registerContentObserver(this.selectUri, true, observer);
}
}
public void unregisterContentObserver(ContentObserver observer) {
if (observer != null) {
this.mContext.getContentResolver().unregisterContentObserver(observer);
}
}
private static class LazyHold {
static final WhhConfigManager sInstance = new WhhConfigManager();
private LazyHold() {
}
}
}