將ContentProvider封裝成SharedPreference相同使用方式
一、初略介紹
ContentProvider,即內容提供者,是 Android 四大元件之一。主要功能是程序間資料互動/共享。詳細內容請看這篇文章:Android:關於ContentProvider的知識都在這裡了!
二、程式碼實現
1、首先要在一個應用中註冊ContentProvider元件
/** * 定義一個儲存contentprovider資料的資料庫 */ 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中靜態註冊 */ 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..."); //在這建立資料庫 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()); } } //返回資料的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: // 第二個引數是當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中靜態註冊一下ContentProvider <provider android:name=".provider.WhhConfigProvider" android:authorities="com.whh.shareprovider" android:exported="true" /> /** * 資料庫常量類 */ 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() { } } }