基于Android ContentProvider的總結(jié)詳解
1) ContentProvider為存儲(chǔ)和讀取數(shù)據(jù)提供了統(tǒng)一的接口
2) 使用ContentProvider,應(yīng)用程序可以實(shí)現(xiàn)數(shù)據(jù)共享
3) android內(nèi)置的許多數(shù)據(jù)都是使用ContentProvider形式,供開(kāi)發(fā)者調(diào)用的(如視頻,音頻,圖片,通訊錄等)
2.相關(guān)概念介紹
1)ContentProvider簡(jiǎn)介
當(dāng)應(yīng)用繼承ContentProvider類,并重寫該類用于提供數(shù)據(jù)和存儲(chǔ)數(shù)據(jù)的方法,就可以向其他應(yīng)用共享其數(shù)據(jù)。雖然使用其他方法也可以對(duì)外共享數(shù)據(jù),但數(shù)據(jù)訪問(wèn)方式會(huì)因數(shù)據(jù)存儲(chǔ)的方式而不同,如:采用文件方式對(duì)外共享數(shù)據(jù),需要進(jìn)行文件操作讀寫數(shù)據(jù);采用sharedpreferences共享數(shù)據(jù),需要使用sharedpreferences API讀寫數(shù)據(jù)。而使用ContentProvider共享數(shù)據(jù)的好處是統(tǒng)一了數(shù)據(jù)訪問(wèn)方式。
2)Uri類簡(jiǎn)介
Uri uri = Uri.parse("content://com.changcheng.provider.contactprovider/contact")
在Content Provider中使用的查詢字符串有別于標(biāo)準(zhǔn)的SQL查詢。很多諸如select, add, delete, modify等操作我們都使用一種特殊的URI來(lái)進(jìn)行,這種URI由3個(gè)部分組成, “content://”, 代表數(shù)據(jù)的路徑,和一個(gè)可選的標(biāo)識(shí)數(shù)據(jù)的ID。以下是一些示例URI:
content://media/internal/images 這個(gè)URI將返回設(shè)備上存儲(chǔ)的所有圖片
content://contacts/people/ 這個(gè)URI將返回設(shè)備上的所有聯(lián)系人信息
content://contacts/people/45 這個(gè)URI返回單個(gè)結(jié)果(聯(lián)系人信息中ID為45的聯(lián)系人記錄)
盡管這種查詢字符串格式很常見(jiàn),但是它看起來(lái)還是有點(diǎn)令人迷惑。為此,Android提供一系列的幫助類(在android.provider包下),里面包含了很多以類變量形式給出的查詢字符串,這種方式更容易讓我們理解一點(diǎn),因此,如上面content://contacts/people/45這個(gè)URI就可以寫成如下形式:
Uri person = ContentUris.withAppendedId(People.CONTENT_URI, 45);
然后執(zhí)行數(shù)據(jù)查詢:
Cursor cur = managedQuery(person, null, null, null);
這個(gè)查詢返回一個(gè)包含所有數(shù)據(jù)字段的游標(biāo),我們可以通過(guò)迭代這個(gè)游標(biāo)來(lái)獲取所有的數(shù)據(jù):
package com.wissen.testApp;
public class ContentProviderDemo extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
displayRecords();
}
private void displayRecords() {
//該數(shù)組中包含了所有要返回的字段
String columns[] = new String[] { People.NAME, People.NUMBER };
Uri mContacts = People.CONTENT_URI;
Cursor cur = managedQuery(
mContacts,
columns, // 要返回的數(shù)據(jù)字段
null, // WHERE子句
null, // WHERE 子句的參數(shù)
null // Order-by子句
);
if (cur.moveToFirst()) {
String name = null;
String phoneNo = null;
do {
// 獲取字段的值
name = cur.getString(cur.getColumnIndex(People.NAME));
phoneNo = cur.getString(cur.getColumnIndex(People.NUMBER));
Toast.makeText(this, name + ” ” + phoneNo, Toast.LENGTH_LONG).show();
} while (cur.moveToNext());
}
}
}
上例示范了一個(gè)如何依次讀取聯(lián)系人信息表中的指定數(shù)據(jù)列name和number。
修改記錄:
我們可以使用ContentResolver.update()方法來(lái)修改數(shù)據(jù),我們來(lái)寫一個(gè)修改數(shù)據(jù)的方法:
private void updateRecord(int recNo, String name) {
Uri uri = ContentUris.withAppendedId(People.CONTENT_URI, recNo);
ContentValues values = new ContentValues();
values.put(People.NAME, name);
getContentResolver().update(uri, values, null, null);
}
現(xiàn)在你可以調(diào)用上面的方法來(lái)更新指定記錄:
updateRecord(10, ”XYZ”); //更改第10條記錄的name字段值為“XYZ”
添加記錄:
要增加記錄,我們可以調(diào)用ContentResolver.insert()方法,該方法接受一個(gè)要增加的記錄的目標(biāo)URI,以及一個(gè)包含了新記錄值的Map對(duì)象,調(diào)用后的返回值是新記錄的URI,包含記錄號(hào)。
上面的例子中我們都是基于聯(lián)系人信息簿這個(gè)標(biāo)準(zhǔn)的Content Provider,現(xiàn)在我們繼續(xù)來(lái)創(chuàng)建一個(gè)insertRecord() 方法以對(duì)聯(lián)系人信息簿中進(jìn)行數(shù)據(jù)的添加:
private void insertRecords(String name, String phoneNo) {
ContentValues values = new ContentValues();
values.put(People.NAME, name);
Uri uri = getContentResolver().insert(People.CONTENT_URI, values);
Log.d(”ANDROID”, uri.toString());
Uri numberUri = Uri.withAppendedPath(uri, People.Phones.CONTENT_DIRECTORY);
values.clear();
values.put(Contacts.Phones.TYPE, People.Phones.TYPE_MOBILE);
values.put(People.NUMBER, phoneNo);
getContentResolver().insert(numberUri, values);
}
這樣我們就可以調(diào)用insertRecords(name, phoneNo)的方式來(lái)向聯(lián)系人信息簿中添加聯(lián)系人姓名和電話號(hào)碼。
刪除記錄:
Content Provider中的getContextResolver.delete()方法可以用來(lái)刪除記錄,下面的記錄用來(lái)刪除設(shè)備上所有的聯(lián)系人信息:
private void deleteRecords() {
Uri uri = People.CONTENT_URI;
getContentResolver().delete(uri, null, null);
}
你也可以指定WHERE條件語(yǔ)句來(lái)刪除特定的記錄:
getContentResolver().delete(uri, “NAME=” + “‘XYZ XYZ'”, null);
這將會(huì)刪除name為‘XYZ XYZ'的記錄。
3. 創(chuàng)建ContentProvider
要?jiǎng)?chuàng)建我們自己的Content Provider的話,我們需要遵循以下幾步:
a. 創(chuàng)建一個(gè)繼承了ContentProvider父類的類
b. 定義一個(gè)名為CONTENT_URI,并且是public static final的Uri類型的類變量,你必須為其指定一個(gè)唯一的字符串值,最好的方案是以類的全名稱, 如:
public static final Uri CONTENT_URI = Uri.parse( “content://com.google.android.MyContentProvider”);
c. 定義你要返回給客戶端的數(shù)據(jù)列名。如果你正在使用Android數(shù)據(jù)庫(kù),必須為其定義一個(gè)叫_id的列,它用來(lái)表示每條記錄的唯一性。
d. 創(chuàng)建你的數(shù)據(jù)存儲(chǔ)系統(tǒng)。大多數(shù)Content Provider使用Android文件系統(tǒng)或SQLite數(shù)據(jù)庫(kù)來(lái)保持?jǐn)?shù)據(jù),但是你也可以以任何你想要的方式來(lái)存儲(chǔ)。
e. 如果你要存儲(chǔ)字節(jié)型數(shù)據(jù),比如位圖文件等,數(shù)據(jù)列其實(shí)是一個(gè)表示實(shí)際保存文件的URI字符串,通過(guò)它來(lái)讀取對(duì)應(yīng)的文件數(shù)據(jù)。處理這種數(shù)據(jù)類型的Content Provider需要實(shí)現(xiàn)一個(gè)名為_(kāi)data的字段,_data字段列出了該文件在Android文件系統(tǒng)上的精確路徑。這個(gè)字段不僅是供客戶端使用,而且也可以供ContentResolver使用??蛻舳丝梢哉{(diào)用ContentResolver.openOutputStream()方法來(lái)處理該URI指向的文件資源;如果是ContentResolver本身的話,由于其持有的權(quán)限比客戶端要高,所以它能直接訪問(wèn)該數(shù)據(jù)文件。
f. 聲明public static String型的變量,用于指定要從游標(biāo)處返回的數(shù)據(jù)列。
g. 查詢返回一個(gè)Cursor類型的對(duì)象。所有執(zhí)行寫操作的方法如insert(), update() 以及delete()都將被監(jiān)聽(tīng)。我們可以通過(guò)使用ContentResover().notifyChange()方法來(lái)通知監(jiān)聽(tīng)器關(guān)于數(shù)據(jù)更新的信息。
h. 在AndroidMenifest.xml中使用<provider>標(biāo)簽來(lái)設(shè)置Content Provider。
i. 如果你要處理的數(shù)據(jù)類型是一種比較新的類型,你就必須先定義一個(gè)新的MIME類型,以供ContentProvider.geType(url)來(lái)返回。MIME類型有兩種形式:一種是為指定的單個(gè)記錄的,還有一種是為多條記錄的。這里給出一種常用的格式:
vnd.android.cursor.item/vnd.yourcompanyname.contenttype (單個(gè)記錄的MIME類型)
比如, 一個(gè)請(qǐng)求列車信息的URI如content://com.example.transportationprovider/trains/122 可能就會(huì)返回typevnd.android.cursor.item/vnd.example.rail這樣一個(gè)MIME類型。
vnd.android.cursor.dir/vnd.yourcompanyname.contenttype (多個(gè)記錄的MIME類型)
比如, 一個(gè)請(qǐng)求所有列車信息的URI如content://com.example.transportationprovider/trains 可能就會(huì)返回vnd.android.cursor.dir/vnd.example.rail這樣一個(gè)MIME 類型。
下列代碼將創(chuàng)建一個(gè)Content Provider,它僅僅是存儲(chǔ)用戶名稱并顯示所有的用戶名稱(使用 SQLLite數(shù)據(jù)庫(kù)存儲(chǔ)這些數(shù)據(jù)):
public class MyUsers {
public static final String AUTHORITY = “com.wissen.MyContentProvider”;
// BaseColumn類中已經(jīng)包含了 _id字段
public static final class User implements BaseColumns {
public static final Uri CONTENT_URI = Uri.parse(”content://com.wissen.MyContentProvider”);
// 表數(shù)據(jù)列
public static final String USER_NAME = “USER_NAME”;
}
}
上面的類中定義了Content Provider的CONTENT_URI,以及數(shù)據(jù)列。下面我們將定義基于上面的類來(lái)定義實(shí)際的Content Provider類:
public class MyContentProvider extends ContentProvider {
private SQLiteDatabase sqlDB;
private DatabaseHelper dbHelper;
private static final String DATABASE_NAME = “Users.db”;
private static final int DATABASE_VERSION= 1;
private static final String TABLE_NAME= “User”;
private static final String TAG = “MyContentProvider”;
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
//創(chuàng)建用于存儲(chǔ)數(shù)據(jù)的表
db.execSQL(”Create table ” + TABLE_NAME + “( _id INTEGER PRIMARY KEY AUTOINCREMENT, USER_NAME TEXT);”);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(”DROP TABLE IF EXISTS ” + TABLE_NAME);
onCreate(db);
}
}
@Override
public int delete(Uri uri, String s, String[] as) {
return 0;
}
@Override
public String getType(Uri uri) {
return null;
}
@Override
public Uri insert(Uri uri, ContentValues contentvalues) {
sqlDB = dbHelper.getWritableDatabase();
long rowId = sqlDB.insert(TABLE_NAME, “”, contentvalues);
if (rowId > 0) {
Uri rowUri = ContentUris.appendId(MyUsers.User.CONTENT_URI.buildUpon(), rowId).build();
getContext().getContentResolver().notifyChange(rowUri, null);
return rowUri;
}
throw new SQLException(”Failed to insert row into ” + uri);
}
@Override
public boolean onCreate() {
dbHelper = new DatabaseHelper(getContext());
return (dbHelper == null) ? false : true;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
SQLiteDatabase db = dbHelper.getReadableDatabase();
qb.setTables(TABLE_NAME);
Cursor c = qb.query(db, projection, selection, null, null, null, sortOrder);
c.setNotificationUri(getContext().getContentResolver(), uri);
return c;
}
@Override
public int update(Uri uri, ContentValues contentvalues, String s, String[] as) {
return 0;
}
}
一個(gè)名為MyContentProvider的Content Provider創(chuàng)建完成了,它用于從Sqlite數(shù)據(jù)庫(kù)中添加和讀取記錄。
Content Provider的入口需要在AndroidManifest.xml中配置:
<provider android:name=”MyContentProvider” android:authorities=”com.wissen.MyContentProvider” />
之后,讓我們來(lái)使用這個(gè)定義好的Content Provider:
1)為應(yīng)用程序添加ContentProvider的訪問(wèn)權(quán)限。
2)通過(guò)getContentResolver()方法得到ContentResolver對(duì)象。
3)調(diào)用ContentResolver類的query()方法查詢數(shù)據(jù),該方法會(huì)返回一個(gè)Cursor對(duì)象。
4)對(duì)得到的Cursor對(duì)象進(jìn)行分析,得到需要的數(shù)據(jù)。
5)調(diào)用Cursor類的close()方法將Cursor對(duì)象關(guān)閉。
public class MyContentDemo extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
insertRecord(”MyUser”);
displayRecords();
}
private void insertRecord(String userName) {
ContentValues values = new ContentValues();
values.put(MyUsers.User.USER_NAME, userName);
getContentResolver().insert(MyUsers.User.CONTENT_URI, values);
}
private void displayRecords() {
String columns[] = new String[] { MyUsers.User._ID, MyUsers.User.USER_NAME };
Uri myUri = MyUsers.User.CONTENT_URI;
Cursor cur = managedQuery(myUri, columns,null, null, null );
if (cur.moveToFirst()) {
String id = null;
String userName = null;
do {
id = cur.getString(cur.getColumnIndex(MyUsers.User._ID));
userName = cur.getString(cur.getColumnIndex(MyUsers.User.USER_NAME));
Toast.makeText(this, id + ” ” + userName, Toast.LENGTH_LONG).show();
} while (cur.moveToNext());
}
}
}
- Android開(kāi)發(fā)之ContentProvider的使用詳解
- Android中自定義ContentProvider實(shí)例
- 實(shí)例講解Android中ContentProvider組件的使用方法
- Android中自定義ContentProvider實(shí)例
- 深入U(xiǎn)nderstanding Android ContentProvider詳解
- Android編程使用內(nèi)容提供者方式(ContentProvider)進(jìn)行存儲(chǔ)的方法
- Android內(nèi)容提供者ContentProvider用法實(shí)例分析
- Android編程之創(chuàng)建自己的內(nèi)容提供器實(shí)現(xiàn)方法
相關(guān)文章
Android中三種onClick的實(shí)現(xiàn)方式與對(duì)比
這篇文章主要為大家詳細(xì)介紹了Android中三種onClick的實(shí)現(xiàn)方式以及詳細(xì)對(duì)比,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2025-04-04
Android 實(shí)現(xiàn)文件夾排序功能的實(shí)例代碼
這篇文章主要介紹了Android 實(shí)現(xiàn)文件夾排序功能的實(shí)例代碼,非常不錯(cuò),具有一定的參考借鑒價(jià)值 ,需要的朋友可以參考下2018-09-09
Android RecyclerView仿新聞?lì)^條的頻道管理功能
這篇文章主要介紹了Android RecyclerView仿新聞?lì)^條的頻道管理功能,需要的朋友可以參考下2017-06-06
基于Android studio3.6的JNI教程之opencv實(shí)例詳解
這篇文章主要介紹了基于Android studio3.6的JNI教程之opencv實(shí)例詳解,本文通過(guò)實(shí)例代碼截圖的形式給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-03-03
Android開(kāi)發(fā)實(shí)現(xiàn)自定義水平滾動(dòng)的容器示例
這篇文章主要介紹了Android開(kāi)發(fā)實(shí)現(xiàn)自定義水平滾動(dòng)的容器,涉及Android滾動(dòng)容器的事件響應(yīng)、屬性運(yùn)算與修改相關(guān)操作技巧,需要的朋友可以參考下2017-10-10
Android中的popupwindow進(jìn)入和退出的動(dòng)畫效果
這篇文章主要介紹了Android中的popupwindow進(jìn)入和退出的動(dòng)畫,需要的朋友可以參考下2017-04-04
Android使用MediaCodec將攝像頭采集的視頻編碼為h264
這篇文章主要為大家詳細(xì)介紹了Android使用MediaCodec將攝像頭采集的視頻編碼為h264,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-10-10
Android中的人臉檢測(cè)的示例代碼(靜態(tài)和動(dòng)態(tài))
本篇文章主要介紹了Android中的人臉檢測(cè)的示例代碼(靜態(tài)和動(dòng)態(tài)),小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-01-01
Android中實(shí)現(xiàn)圖文并茂的按鈕實(shí)例代碼
這篇文章主要介紹了Android中實(shí)現(xiàn)圖文并茂的按鈕實(shí)例代碼,代碼簡(jiǎn)單易懂,非常不錯(cuò),需要的朋友可以參考下2017-04-04

