將ContentProvider封裝成SharedPreference相同使用方式

一、初略介紹

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() {
        }
    }
}
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市家夺,隨后出現(xiàn)的幾起案子脱柱,更是在濱河造成了極大的恐慌,老刑警劉巖拉馋,帶你破解...
    沈念sama閱讀 207,113評論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件榨为,死亡現(xiàn)場離奇詭異,居然都是意外死亡煌茴,警方通過查閱死者的電腦和手機随闺,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,644評論 2 381
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來蔓腐,“玉大人矩乐,你說我怎么就攤上這事』芈郏” “怎么了散罕?”我有些...
    開封第一講書人閱讀 153,340評論 0 344
  • 文/不壞的土叔 我叫張陵,是天一觀的道長傀蓉。 經常有香客問我欧漱,道長,這世上最難降的妖魔是什么葬燎? 我笑而不...
    開封第一講書人閱讀 55,449評論 1 279
  • 正文 為了忘掉前任误甚,我火速辦了婚禮,結果婚禮上萨蚕,老公的妹妹穿的比我還像新娘靶草。我一直安慰自己,他們只是感情好岳遥,可當我...
    茶點故事閱讀 64,445評論 5 374
  • 文/花漫 我一把揭開白布奕翔。 她就那樣靜靜地躺著,像睡著了一般浩蓉。 火紅的嫁衣襯著肌膚如雪派继。 梳的紋絲不亂的頭發(fā)上宾袜,一...
    開封第一講書人閱讀 49,166評論 1 284
  • 那天,我揣著相機與錄音驾窟,去河邊找鬼庆猫。 笑死,一個胖子當著我的面吹牛绅络,可吹牛的內容都是我干的月培。 我是一名探鬼主播,決...
    沈念sama閱讀 38,442評論 3 401
  • 文/蒼蘭香墨 我猛地睜開眼恩急,長吁一口氣:“原來是場噩夢啊……” “哼杉畜!你這毒婦竟也來了?” 一聲冷哼從身側響起衷恭,我...
    開封第一講書人閱讀 37,105評論 0 261
  • 序言:老撾萬榮一對情侶失蹤此叠,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后随珠,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體灭袁,經...
    沈念sama閱讀 43,601評論 1 300
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 36,066評論 2 325
  • 正文 我和宋清朗相戀三年窗看,在試婚紗的時候發(fā)現(xiàn)自己被綠了茸歧。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 38,161評論 1 334
  • 序言:一個原本活蹦亂跳的男人離奇死亡烤芦,死狀恐怖举娩,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情构罗,我是刑警寧澤铜涉,帶...
    沈念sama閱讀 33,792評論 4 323
  • 正文 年R本政府宣布,位于F島的核電站遂唧,受9級特大地震影響芙代,放射性物質發(fā)生泄漏。R本人自食惡果不足惜盖彭,卻給世界環(huán)境...
    茶點故事閱讀 39,351評論 3 307
  • 文/蒙蒙 一纹烹、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧召边,春花似錦铺呵、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,352評論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春音念,著一層夾襖步出監(jiān)牢的瞬間沪饺,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 31,584評論 1 261
  • 我被黑心中介騙來泰國打工闷愤, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留整葡,地道東北人。 一個月前我還...
    沈念sama閱讀 45,618評論 2 355
  • 正文 我出身青樓讥脐,卻偏偏與公主長得像遭居,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子旬渠,可洞房花燭夜當晚...
    茶點故事閱讀 42,916評論 2 344

推薦閱讀更多精彩內容