ContentProvider使用示例

1赴蝇、MyContentProvider

public class MyContentProviderextends ContentProvider {

private static final StringTAG ="MyContentProvider";

? ? private Contextcontext;

? ? private SQLiteDatabasesqLiteDatabase;

? ? public static final StringAUTHORITY ="com.examp.mycontentprovider.MyContentProvider";

? ? public static final int PROVIDER_CODE =0;

? ? private static final UriMatcheruriMatcher =new UriMatcher(UriMatcher.NO_MATCH);

? ? static {

????????????uriMatcher.addURI(AUTHORITY, MyDBHelper.TABLE_NAME, PROVIDER_CODE);

? ? }

????public MyContentProvider() {

????}

????/**

????* 通過uri匹配表名

????*

? ? * @param uri

? ? * @return

? ? */

? ? private StringgetTableName(Uri uri) {

????????String tableName =null;

? ? ? ? switch (uriMatcher.match(uri)) {

????????????????case PROVIDER_CODE:

????????????????tableName = MyDBHelper.TABLE_NAME;

????????????????break;

? ? ? ? }

????????return tableName;

? ? }

@Override

? ? public boolean onCreate() {

????????????init();

????return false;

? ? }

????private void init() {

????????context = getContext();

? ? ? ? sqLiteDatabase =new MyDBHelper(context).getWritableDatabase();

? ? }

@Nullable

@Override

? ? public Cursorquery(@NonNull Uri uri, @Nullable String[] projection, @Nullable String selection, @Nullable String[] selectionArgs, @Nullable String sortOrder) {

????????String tableName = getTableName(uri);

? ? ? ? if (tableName ==null) {

????????????Log.e(TAG, "query: 未匹配到uri");

? ? ? ? ? ? throw new IllegalArgumentException("Unsupported URI:" + uri);

? ? ? ? }

????????return sqLiteDatabase.query(tableName, projection, selection, selectionArgs, null, null, ????????????sortOrder, null);

? ? }

@Nullable

@Override

? ? public StringgetType(@NonNull Uri uri) {

????????return null;

? ? }

????@Nullable

????@Override

? ? public Uriinsert(@NonNull Uri uri, @Nullable ContentValues values) {

????????????String tableName = getTableName(uri);

? ? ? ????? if (tableName ==null) {

????????????Log.e(TAG, "insert: 未匹配到uri");

? ? ? ? ? ? throw new IllegalArgumentException("Unsupported URI:" + uri);

? ? ? ? ????}

????????????sqLiteDatabase.insert(tableName, null, values);

? ? ? ????? context.getContentResolver().notifyChange(uri, null);

? ? ? ????? Log.d(TAG, "insert: 添加成功");

? ? ? ? ????return uri;

? ? }

????@Override

? ? public int delete(@NonNull Uri uri, @Nullable String selection, @Nullable String[] selectionArgs) {

????????????String tableName = getTableName(uri);

? ? ? ????? if (tableName ==null) {

????????????Log.e(TAG, "delete: 未匹配到uri");

? ? ? ? ? ? throw new IllegalArgumentException("Unsupported URI:" + uri);

? ? ? ? ????}

????????????int count =sqLiteDatabase.delete(tableName, selection, selectionArgs);

? ? ? ????? if (count >0) {

????????????context.getContentResolver().notifyChange(uri, null);

? ? ? ? }

????????????Log.d(TAG, "delete: 刪除成功");

? ? ? ? ????Log.d(TAG, "delete: count=" + count);

? ? ? ? return count;

? ? }

????@Override

? ? public int update(@NonNull Uri uri, @Nullable ContentValues values, @Nullable String selection, @Nullable String[] selectionArgs) {

????????????String tableName = getTableName(uri);

? ? ? ????? if (tableName ==null) {

????????????????throw new IllegalArgumentException("Unsupported URI:" + uri);

? ? ? ? ????}

????????????int row =sqLiteDatabase.update(tableName, values, selection, selectionArgs);

? ? ? ????? if (row >0) {

????????????????context.getContentResolver().notifyChange(uri, null);

? ? ? ? }

????????return row;

? ? }

}


2、MyDBHelper

public class MyDBHelperextends SQLiteOpenHelper {

/**

* 庫名

*/

? ? private static final StringDBNAME ="provider.db";

? ? /**

* 表明 測試用

*/

? ? public static final StringTABLE_NAME ="provider_data";

? ? /**

* 版本號

*/

? ? private static final int VERSION =1;

? ? /**

????* 建表的sql語句

????*/

? ? private static final StringSQL ="create table " +TABLE_NAME +"(id integer primary key Autoincrement,name text)";

? ? private Contextcontext;

? ? public MyDBHelper(Context context) {

????????super(context, DBNAME, null, VERSION);

? ? ? ? this.context = context;

? ? }

@Override

? ? public void onCreate(SQLiteDatabase db) {

????????db.execSQL(SQL);

? ? ? ? Toast.makeText(context, "建表成功", Toast.LENGTH_SHORT).show();

? ? ? ? Log.d("MyContentProvider", "onCreate: 建表成功");

? ? }

????@Override

? ? public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

????}

}


3膘掰、在MainActivity中使用

public class MainActivityextends AppCompatActivityimplements View.OnClickListener {

private static final StringTAG ="MyContentProvider";

? ? @Override

? ? protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

? ? ? ? setContentView(R.layout.activity_main);

? ? ? ? initView();

? ? }

private void initView() {

????????Button bt_init = findViewById(R.id.bt_init);

? ? ? ? bt_init.setOnClickListener(this);

? ? ? ? Button bt_add = findViewById(R.id.bt_add);

? ? ? ? bt_add.setOnClickListener(this);

? ? ? ? Button bt_delete = findViewById(R.id.bt_delete);

? ? ? ? bt_delete.setOnClickListener(this);

? ? ? ? Button bt_update = findViewById(R.id.bt_update);

? ? ? ? bt_update.setOnClickListener(this);

? ? ? ? Button bt_query = findViewById(R.id.bt_query);

? ? ? ? bt_query.setOnClickListener(this);

? ? }

@Override

? ? public void onClick(View v) {

????????switch (v.getId()) {

????????????case R.id.bt_init:

????????????????????init();

????????????????break;

? ? ? ? ? ? case R.id.bt_add:

????????????????????toAdd();

????????????????break;

? ? ? ? ? ? case R.id.bt_delete:

????????????????toDelete();

????????????????break;

? ? ? ? ? ? case R.id.bt_update:

????????????????toUpdate();

????????????break;

? ? ? ? ? ? case R.id.bt_query:

????????????????toQuery();

????????????break;

? ? ? ? }

}

????private void init() {

????????getContentResolver().delete(nameUri, null, null);

? ? }

????private UrinameUri = Uri.parse("content://com.examp.mycontentprovider.MyContentProvider/provider_data");

? ? private void toAdd() {

????????ContentValues contentValues =new ContentValues();

? ? ? ? contentValues.put("name", "水貨");

? ? ? ? getContentResolver().insert(nameUri, contentValues);

? ? }

????private void toDelete() {

????????????getContentResolver().delete(nameUri, "name=?", new String[]{"水貨"});

? ? }

????private void toUpdate() {

????????ContentValues contentValues =new ContentValues();

? ? ? ? contentValues.put("name", "太陽");

? ? ? ? getContentResolver().update(nameUri, contentValues, "id=?", new String[]{"21"});

? ? }

private void toQuery() {

????????????Cursor nameCursor = getContentResolver().query(nameUri, new String[]{"id", "name"}, null, null, null);

? ? ? ? ????if (nameCursor !=null) {

????????????????while (nameCursor.moveToNext()) {

????????????????Log.e(TAG, "id:" + nameCursor.getInt(nameCursor.getColumnIndex("id"))

????????????????+" name:" + nameCursor.getString(nameCursor.getColumnIndex("name")));

? ? ? ? ? ? }

????????????????Log.d(TAG, "toQuery: 查詢成功");

? ? ? ? ? ????? nameCursor.close();

? ? ? ? }

????}

}


4识埋、activity_main.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

? ? xmlns:tools="http://schemas.android.com/tools"

? ? android:layout_width="match_parent"

? ? android:layout_height="match_parent"

? ? android:gravity="center_horizontal"

? ? android:orientation="vertical"

? ? tools:context=".MainActivity">

? ? ? ? android:id="@+id/bt_init"

? ? ? ? android:layout_width="wrap_content"

? ? ? ? android:layout_height="wrap_content"

? ? ? ? android:text="初始化" />

? ? ? ? android:id="@+id/bt_add"

? ? ? ? android:layout_width="wrap_content"

? ? ? ? android:layout_height="wrap_content"

? ? ? ? android:text="添加" />

? ? ? ? android:id="@+id/bt_delete"

? ? ? ? android:layout_width="wrap_content"

? ? ? ? android:layout_height="wrap_content"

? ? ? ? android:text="刪除" />

? ? ? ? android:id="@+id/bt_update"

? ? ? ? android:layout_width="wrap_content"

? ? ? ? android:layout_height="wrap_content"

? ? ? ? android:text="更新" />

? ? ? ? android:id="@+id/bt_query"

? ? ? ? android:layout_width="wrap_content"

? ? ? ? android:layout_height="wrap_content"

? ? ? ? android:text="查詢" />

</LinearLayout>


5窒舟、manifest

<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

? ? package="com.examp.mycontentprovider">

? ? ? ? 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">

? ? ? ? <activity android:name=".MainActivity">

? ? ? ? ? ? ? ? <action android:name="android.intent.action.MAIN" />

? ? ? ? ? ? ? ? <category android:name="android.intent.category.LAUNCHER" />

? ? ? ? ? ? android:name=".MyContentProvider"

? ? ? ? ? ? android:authorities="com.examp.mycontentprovider.MyContentProvider"

? ? ? ? ? ? android:exported="true"/>

</manifest>

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末惠豺,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子洁墙,更是在濱河造成了極大的恐慌,老刑警劉巖捺弦,帶你破解...
    沈念sama閱讀 219,188評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件孝扛,死亡現(xiàn)場離奇詭異,居然都是意外死亡寞钥,警方通過查閱死者的電腦和手機盈简,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,464評論 3 395
  • 文/潘曉璐 我一進店門香浩,熙熙樓的掌柜王于貴愁眉苦臉地迎上來邻吭,“玉大人,你說我怎么就攤上這事囱晴∑靶唬” “怎么了?”我有些...
    開封第一講書人閱讀 165,562評論 0 356
  • 文/不壞的土叔 我叫張陵论笔,是天一觀的道長千所。 經(jīng)常有香客問我,道長最楷,這世上最難降的妖魔是什么待错? 我笑而不...
    開封第一講書人閱讀 58,893評論 1 295
  • 正文 為了忘掉前任,我火速辦了婚禮火俄,結(jié)果婚禮上烛占,老公的妹妹穿的比我還像新娘忆家。我一直安慰自己德迹,他們只是感情好胳搞,可當我...
    茶點故事閱讀 67,917評論 6 392
  • 文/花漫 我一把揭開白布筷转。 她就那樣靜靜地躺著悬而,像睡著了一般笨奠。 火紅的嫁衣襯著肌膚如雪般婆。 梳的紋絲不亂的頭發(fā)上蔚袍,一...
    開封第一講書人閱讀 51,708評論 1 305
  • 那天,我揣著相機與錄音段誊,去河邊找鬼栈拖。 笑死涩哟,一個胖子當著我的面吹牛贴彼,可吹牛的內(nèi)容都是我干的器仗。 我是一名探鬼主播精钮,決...
    沈念sama閱讀 40,430評論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼轨香,長吁一口氣:“原來是場噩夢啊……” “哼臂容!你這毒婦竟也來了脓杉?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,342評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎吼畏,沒想到半個月后嘁灯,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體丑婿,經(jīng)...
    沈念sama閱讀 45,801評論 1 317
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,976評論 3 337
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了迁筛。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片细卧。...
    茶點故事閱讀 40,115評論 1 351
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖止邮,靈堂內(nèi)的尸體忽然破棺而出导披,到底是詐尸還是另有隱情盛卡,我是刑警寧澤,帶...
    沈念sama閱讀 35,804評論 5 346
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響棚潦,放射性物質(zhì)發(fā)生泄漏丸边。R本人自食惡果不足惜妹窖,卻給世界環(huán)境...
    茶點故事閱讀 41,458評論 3 331
  • 文/蒙蒙 一骄呼、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧澄峰,春花似錦辟犀、人聲如沸踪蹬。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,008評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽娶聘。三九已至,卻和暖如春铆农,著一層夾襖步出監(jiān)牢的瞬間墩剖,已是汗流浹背夷狰。 一陣腳步聲響...
    開封第一講書人閱讀 33,135評論 1 272
  • 我被黑心中介騙來泰國打工爷绘, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留土至,地道東北人猾昆。 一個月前我還...
    沈念sama閱讀 48,365評論 3 373
  • 正文 我出身青樓坑赡,卻偏偏與公主長得像烙如,于是被迫代替她去往敵國和親亚铁。 傳聞我的和親對象是個殘疾皇子徘溢,可洞房花燭夜當晚...
    茶點故事閱讀 45,055評論 2 355