ContentProvider简介

本文详细介绍了Android中的ContentProvider组件,包括其基本概念、如何通过Uri指定数据路径、使用UriMatcher匹配Uri以及ContentResolver进行数据操作。此外,还展示了ContentProvider需要实现的主要方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

ContentProvider

一、ContentProvider简介

当应用继承ContentProvider类,并重写该类用于提供数据和存储数据的方法,就可以向其他应用共享其数据。使用ContentProvider共享数据的好处是统一了数据访问方式。

二、Uri类简介

Uri代表了要操作的数据,Uri主要包含了两部分信息:

1.需要操作的ContentProvider

2.对ContentProvider中的什么数据进行操作,一个Uri由以下几部分组成:

如图:URI"content://"+com.android.word.providers +"/words/100"分为四个部分.

A表示该数据又contentprovider控制的标准前缀,不可更改。

B是授权(AUTHORITY)部分,在这个例子里边就是com.android.word.providers,授权部分是惟一的,并且全都小写。这部份是和在AndroidManifest.xml文件当中的<providerandroid:name=".DictProvider"

android:authorities="com.android.word.providers" />部分对应的。外部调用者可以根据这个标识来找到它。

Cpath,可以用来表示我们要操作的数据。路径根据业务而定,例如,

如要操作dict表中id为2的记录,可以构建这样的路径:

“content://com.android.word.providers/words/2”

要操作dict表中的所有记录,可以构建这样的路径:

“content://com.android.word.providers/words”

如果要把一个字符串转换成Uri,可以使用Uri类中的parse()方法,如下:

Uri uri = Uri.parse("content://com.android.word.providers/words"")

 

三、UriMatcher、ContentUris和ContentResolver简介

    因为Uri代表了要操作的数据,所以我们很经常需要解析Uri,并从Uri中获取数据。Android系统提供了两个用于操作Uri的工具类,分别为UriMatcher ContentUris 。掌握它们的使用,会便于我们的开发工作。

 UriMatcher:用于匹配Uri,它的用法如下:

UriMatcher 是匹配Uri的一个辅助类。首先把你需要匹配Uri路径全部给注册上,如下:

例如,在我们的DictProvider中的 static 模块中,有下边的代码:

       matcher = new UriMatcher(UriMatcher.NO_MATCH);

       //UriMatcher注册URI

       matcher.addURI(Words.AUTHORITY, "words", WORDS);

       matcher.addURI(Words.AUTHORITY, "words/#", WORD); //#号为通配符

//常量UriMatcher.NO_MATCH表示不匹配任何路径的返回码(-1),

代码解释: WORDSWORD必须为正数

matcher.addURI(Words.AUTHORITY, "words", WORDS), matcher.match(uri))表示我们的 Uri 是content://com.android.word.providers/words

那么 matcher.match(uri)  的返回值就是WORDS。 (WORDS=0

matcher.addURI(Words.AUTHORITY, "words/#", WORD)表示,如果我们的 Uri是

content://com.android.word.providers/words/id(其中后边的 id 是一个数字),那么matcher.match(uri)的返回值就是WORD。 (WORD=1

通过UriMatcher 类我们可以很方便的判断一个URi的类型,特别是判断这个 Uri是对单个数据的请求,还是对全部数据的请求。

 

ContentUrisContentUris是 content URI 的一个辅助类。它有两个方法很有用,如下:

public static Uri withAppendedId(UricontentUri, long id),这个方法负责把 id 和 contentUri连接成一个新的Uri。比如在我们这个例子当中是这么使用的:ContentUris.withAppendedIdWords.Word.DICT_URI, rowId).

如果rowId为100的话,那么现在的这个 Uri的内容就是:   

content://com.android.word.providers/words/100.

public static long parseId(Uri contentUri),这个方法负责把 content URI 后边的 id解析出来.比如现在这个 content URI  是 content://com.android.word.providers/words/100,那么这个函数的返回值就是100.

 

ContentResolver:当外部应用需要对ContentProvider中的数据进行添加、删除、修改和查询操作时,可以使用ContentResolver 类来完成,要获取ContentResolver 对象,可以使用Activity提供的getContentResolver()方法。 ContentResolver使用insertdeleteupdatequery方法,来操作数据。

四、Content Provider需要实现的几个方法

public boolean  onCreate(),当 ContentProvider 生成的时候调用此方法

public Cursorquery(Uri uri, String[] projection, String selection,String[] selectionArgs,String sortOrder) ,此方法返回一个 Cursor 对象作为查询结果集。

        

 publicCursor query(Uri uri, String[] projection, String selection,

                            String[]selectionArgs, String sortOrder) {

                   SQLiteDatabasedb = mHelper.getWritableDatabase();

                   switch(matcher.match(uri)) { //返回一个URI相匹配给定的组件。必须为正数。

                   caseWORDS:

                            //执行查询

                            returndb.query(MyDatabaseHelper.DB_TABLE, projection, selection, selectionArgs, null,null, sortOrder);

                   caseWORD:

           //解析出所需要删除的记录ID

           longid = ContentUris.parseId(uri);

           returndb.query(MyDatabaseHelper.DB_TABLE, projection, "_id=?", newString[]{id+""}, null, null, sortOrder);

                   default:

                            thrownew IllegalArgumentException("未知URI:"+uri);

                   }

         }

public Uri insert(Uriuri, ContentValues initialValues),此方法负责往数据集当中插入一列,并返回这一列的 Uri。

         publicUri insert(Uri uri, ContentValues values) {

                   //TODO Auto-generated method stub

                   //获取数据库实例

                   SQLiteDatabasedb = mHelper.getWritableDatabase();

                   longrowId = db.insert(MyDatabaseHelper.DB_TABLE, null, values);

                   if(rowId> 0 ){

                            //在已有的Uri后面追加Id数据

                            UriwordUri = ContentUris.withAppendedId(uri, rowId);

//由于这些ContentProvider方法能够被不同的ContentResolver对象在不同的进行和线程中调用,因此它们必须是线程安全的。

 //   当数据有改动时,可能需要调用ContentResolver.notifyChange()方法来通知监听器

                            getContext().getContentResolver().notifyChange(wordUri,null);

                            returnwordUri;

                   }

                   returnnull;

         }

public int delete(Uriuri, String where, String[] whereArgs),此方法负责删除指定 Uri的数据。

public int delete(Uri uri, String selection,String[] selectionArgs) {

       SQLiteDatabasedb = mHelper.getWritableDatabase();

       intnum = 0;

       switch(matcher.match(uri)) {  //返回一个URI相匹配给定的组件。必须为正数。

       caseWORDS:

           num= db.delete(MyDatabaseHelper.DB_TABLE, selection, selectionArgs);

           break;

       caseWORD:

           //解析出所需要删除的记录ID

           longid = ContentUris.parseId(uri);

           num= db.delete(MyDatabaseHelper.DB_TABLE, "_id=?", newString[]{id+""});

           break;

       default:

           thrownew IllegalArgumentException("未知URI:"+uri);

       }

       //通知数据已经改变

       getContext().getContentResolver().notifyChange(uri,null);

       returnnum;

    }

public int update(Uriuri, ContentValues values, String where,String[] whereArgs)  ,此方法负责更新指定Uri的数据。 

         publicint update(Uri uri, ContentValues values, String selection,

                            String[]selectionArgs) {

                   SQLiteDatabasedb = mHelper.getWritableDatabase();

                   //记录所修改的记录数

                   intnum = 0;

                   switch(matcher.match(uri)) { //返回一个URI相匹配给定的组件。必须为正数。

                   caseWORDS:

                            num= db.update(MyDatabaseHelper.DB_TABLE, values, selection, selectionArgs);

                            break;

                   caseWORD:

                            //解析出所需要删除的记录ID

           longid = ContentUris.parseId(uri);

           num =db.update(MyDatabaseHelper.DB_TABLE, values, "_id=?", newString[]{id+""});

                            break;

                   default:

                            thrownew IllegalArgumentException("未知URI:"+uri);

                   }

                   //通知数据已经改变

                   getContext().getContentResolver().notifyChange(uri,null);

                   returnnum;

         }

public String getType(Ur

i uri)   //一般不需要实现
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值