內(nèi)容提供者組件通過(guò)請(qǐng)求從一個(gè)應(yīng)用程序向其他的應(yīng)用程序提供數(shù)據(jù)。這些請(qǐng)求由類 ContentResolver 的方法來(lái)處理。內(nèi)容提供者可以使用不同的方式來(lái)存儲(chǔ)數(shù)據(jù)。數(shù)據(jù)可以被存放在數(shù)據(jù)庫(kù),文件,甚至是網(wǎng)絡(luò)。
有時(shí)候需要在應(yīng)用程序之間共享數(shù)據(jù)。這時(shí)內(nèi)容提供者變得非常有用。
內(nèi)容提供者可以讓內(nèi)容集中,必要時(shí)可以有多個(gè)不同的應(yīng)用程序來(lái)訪問(wèn)。內(nèi)容提供者的行為和數(shù)據(jù)庫(kù)很像。你可以查詢,編輯它的內(nèi)容,使用 insert(), update(), delete() 和 query() 來(lái)添加或者刪除內(nèi)容。多數(shù)情況下數(shù)據(jù)被存儲(chǔ)在 SQLite 數(shù)據(jù)庫(kù)。
內(nèi)容提供者被實(shí)現(xiàn)為類 ContentProvider 類的子類。需要實(shí)現(xiàn)一系列標(biāo)準(zhǔn)的 API,以便其他的應(yīng)用程序來(lái)執(zhí)行事務(wù)。
public class MyApplication extends ContentProvider { }
要查詢內(nèi)容提供者,你需要以如下格式的URI的形式來(lái)指定查詢字符串:
<prefix>://<authority>/<data_type>/<id>
以下是URI中各部分的具體說(shuō)明:
部分 | 說(shuō)明 |
---|---|
prefix | 前綴:一直被設(shè)置為content:// |
authority | 授權(quán):指定內(nèi)容提供者的名稱,例如聯(lián)系人,瀏覽器等。第三方的內(nèi)容提供者可以是全名,如:cn.programmer.statusprovider |
data_type | 數(shù)據(jù)類型:這個(gè)表明這個(gè)特殊的內(nèi)容提供者中的數(shù)據(jù)的類型。例如:你要通過(guò)內(nèi)容提供者Contacts來(lái)獲取所有的通訊錄,數(shù)據(jù)路徑是people,那么URI將是下面這樣:content://contacts/people |
id | 這個(gè)指定特定的請(qǐng)求記錄。例如:你在內(nèi)容提供者Contacts中查找聯(lián)系人的ID號(hào)為5,那么URI看起來(lái)是這樣:content://contacts/people/5 |
這里描述創(chuàng)建自己的內(nèi)容提供者的簡(jiǎn)單步驟。
以下是讓你的內(nèi)容提供者正常工作,你需要在類 ContentProvider 中重寫的一些方法:
該實(shí)例解釋如何創(chuàng)建自己的內(nèi)容提供者。讓我們按照下面的步驟:
步驟 | 描述 |
---|---|
1 | 使用 Android Studio 創(chuàng)建 Android 應(yīng)用程序并命名為 Content Provider,在包c(diǎn)n.uprogrammer.contentprovider 下,并建立空活動(dòng)。 |
2 | 修改主要活動(dòng)文件 MainActivity.java 來(lái)添加兩個(gè)新的方法 onClickAddName() 和 onClickRetrieveStudents()。 |
3 | 在包 cn.uprogrammer.contentprovider 下創(chuàng)建新的 Java 文件 StudentsProvider.java 來(lái)定義實(shí)際的提供者,并關(guān)聯(lián)方法。 |
4 | 使用<provider.../>標(biāo)簽在 AndroidManifest.xml 中注冊(cè)內(nèi)容提供者。 |
5 | 修改 res/layout/activity_main.xml 文件的默認(rèn)內(nèi)容來(lái)包含添加學(xué)生記錄的簡(jiǎn)單界面。 |
6 | 無(wú)需修改 strings.xml,Android Studio 會(huì)注意 strings.xml 文件。 |
7 | 啟動(dòng) Android 模擬器來(lái)運(yùn)行應(yīng)用程序,并驗(yàn)證應(yīng)用程序所做改變的結(jié)果。 |
下面是修改的主要活動(dòng)文件 src/cn.uprogrammer.contentprovider/MainActivity.java 的內(nèi)容。該文件包含每個(gè)基礎(chǔ)的生命周期方法。我們添加了兩個(gè)新的方法,onClickAddName() 和 onClickRetrieveStudents() 來(lái)讓應(yīng)用程序處理用戶交互。
package cn.uprogrammer.contentprovider; import android.net.Uri; import android.os.Bundle; import android.app.Activity; import android.content.ContentValues; import android.content.CursorLoader; import android.database.Cursor; import android.view.Menu; import android.view.View; import android.widget.EditText; import android.widget.Toast; import cn.uprogrammer.contentprovider.R; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_main, menu); return true; } public void onClickAddName(View view) { // Add a new student record ContentValues values = new ContentValues(); values.put(StudentsProvider.NAME, ((EditText)findViewById(R.id.editText2)).getText().toString()); values.put(StudentsProvider.GRADE, ((EditText)findViewById(R.id.editText3)).getText().toString()); Uri uri = getContentResolver().insert( StudentsProvider.CONTENT_URI, values); Toast.makeText(getBaseContext(), uri.toString(), Toast.LENGTH_LONG).show(); } public void onClickRetrieveStudents(View view) { // Retrieve student records String URL = "content://com.example.provider.College/students"; Uri students = Uri.parse(URL); Cursor c = managedQuery(students, null, null, null, "name"); if (c.moveToFirst()) { do{ Toast.makeText(this, c.getString(c.getColumnIndex(StudentsProvider._ID)) + ", " + c.getString(c.getColumnIndex( StudentsProvider.NAME)) + ", " + c.getString(c.getColumnIndex( StudentsProvider.GRADE)), Toast.LENGTH_SHORT).show(); } while (c.moveToNext()); } } }
在包c(diǎn)n.uprogrammer.contentprovider下創(chuàng)建新的文件StudentsProvider.java。以下是src/cn.uprogrammer.contentprovider/StudentsProvider.java的內(nèi)容。
package cn.uprogrammer.contentprovider; import java.util.HashMap; import android.content.ContentProvider; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.content.UriMatcher; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteQueryBuilder; import android.net.Uri; import android.text.TextUtils; public class StudentsProvider extends ContentProvider { static final String PROVIDER_NAME = "com.example.provider.College"; static final String URL = "content://" + PROVIDER_NAME + "/students"; static final Uri CONTENT_URI = Uri.parse(URL); static final String _ID = "_id"; static final String NAME = "name"; static final String GRADE = "grade"; private static HashMap<String, String> STUDENTS_PROJECTION_MAP; static final int STUDENTS = 1; static final int STUDENT_ID = 2; static final UriMatcher uriMatcher; static{ uriMatcher = new UriMatcher(UriMatcher.NO_MATCH); uriMatcher.addURI(PROVIDER_NAME, "students", STUDENTS); uriMatcher.addURI(PROVIDER_NAME, "students/#", STUDENT_ID); } /** * 數(shù)據(jù)庫(kù)特定常量聲明 */ private SQLiteDatabase db; static final String DATABASE_NAME = "College"; static final String STUDENTS_TABLE_NAME = "students"; static final int DATABASE_VERSION = 1; static final String CREATE_DB_TABLE = " CREATE TABLE " + STUDENTS_TABLE_NAME + " (_id INTEGER PRIMARY KEY AUTOINCREMENT, " + " name TEXT NOT NULL, " + " grade TEXT NOT NULL);"; /** * 創(chuàng)建和管理提供者內(nèi)部數(shù)據(jù)源的幫助類. */ private static class DatabaseHelper extends SQLiteOpenHelper { DatabaseHelper(Context context){ super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(CREATE_DB_TABLE); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS " + STUDENTS_TABLE_NAME); onCreate(db); } } @Override public boolean onCreate() { Context context = getContext(); DatabaseHelper dbHelper = new DatabaseHelper(context); /** * 如果不存在,則創(chuàng)建一個(gè)可寫的數(shù)據(jù)庫(kù)。 */ db = dbHelper.getWritableDatabase(); return (db == null)? false:true; } @Override public Uri insert(Uri uri, ContentValues values) { /** * 添加新學(xué)生記錄 */ long rowID = db.insert( STUDENTS_TABLE_NAME, "", values); /** * 如果記錄添加成功 */ if (rowID > 0) { Uri _uri = ContentUris.withAppendedId(CONTENT_URI, rowID); getContext().getContentResolver().notifyChange(_uri, null); return _uri; } throw new SQLException("Failed to add a record into " + uri); } @Override public Cursor query(Uri uri, String[] projection, String selection,String[] selectionArgs, String sortOrder) { SQLiteQueryBuilder qb = new SQLiteQueryBuilder(); qb.setTables(STUDENTS_TABLE_NAME); switch (uriMatcher.match(uri)) { case STUDENTS: qb.setProjectionMap(STUDENTS_PROJECTION_MAP); break; case STUDENT_ID: qb.appendWhere( _ID + "=" + uri.getPathSegments().get(1)); break; default: throw new IllegalArgumentException("Unknown URI " + uri); } if (sortOrder == null || sortOrder == ""){ /** * 默認(rèn)按照學(xué)生姓名排序 */ sortOrder = NAME; } Cursor c = qb.query(db, projection, selection, selectionArgs,null, null, sortOrder); /** * 注冊(cè)內(nèi)容URI變化的監(jiān)聽(tīng)器 */ c.setNotificationUri(getContext().getContentResolver(), uri); return c; } @Override public int delete(Uri uri, String selection, String[] selectionArgs) { int count = 0; switch (uriMatcher.match(uri)){ case STUDENTS: count = db.delete(STUDENTS_TABLE_NAME, selection, selectionArgs); break; case STUDENT_ID: String id = uri.getPathSegments().get(1); count = db.delete( STUDENTS_TABLE_NAME, _ID + " = " + id + (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : ""), selectionArgs); break; default: throw new IllegalArgumentException("Unknown URI " + uri); } getContext().getContentResolver().notifyChange(uri, null); return count; } @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { int count = 0; switch (uriMatcher.match(uri)){ case STUDENTS: count = db.update(STUDENTS_TABLE_NAME, values, selection, selectionArgs); break; case STUDENT_ID: count = db.update(STUDENTS_TABLE_NAME, values, _ID + " = " + uri.getPathSegments().get(1) + (!TextUtils.isEmpty(selection) ? " AND (" +selection + ')' : ""), selectionArgs); break; default: throw new IllegalArgumentException("Unknown URI " + uri ); } getContext().getContentResolver().notifyChange(uri, null); return count; } @Override public String getType(Uri uri) { switch (uriMatcher.match(uri)){ /** * 獲取所有學(xué)生記錄 */ case STUDENTS: return "vnd.android.cursor.dir/vnd.example.students"; /** * 獲取一個(gè)特定的學(xué)生 */ case STUDENT_ID: return "vnd.android.cursor.item/vnd.example.students"; default: throw new IllegalArgumentException("Unsupported URI: " + uri); } } }
以下是修改后的AndroidManifest.xml文件。這里添加了<provider.../>標(biāo)簽來(lái)包含我們的內(nèi)容提供者:
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="cn.uprogrammer.contentprovider" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="22" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="cn.uprogrammer.contentprovider.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <provider android:name="StudentsProvider" android:authorities="com.example.provider.College" > </provider> </application> </manifest>
下面是res/layout/activity_main.xml文件的內(nèi)容:
<RelativeLayout 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:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"> <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="內(nèi)容提供者實(shí)例" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:textSize="30dp" /> <TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="www.uprogrammer.cn" android:textColor="#ff87ff09" android:textSize="30dp" android:layout_below="@+id/textView1" android:layout_centerHorizontal="true" /> <ImageButton android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/imageButton" android:src="@drawable/ic_launcher" android:layout_below="@+id/textView2" android:layout_centerHorizontal="true" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/button2" android:text="添加" android:layout_below="@+id/editText3" android:layout_alignRight="@+id/textView2" android:layout_alignEnd="@+id/textView2" android:layout_alignLeft="@+id/textView2" android:layout_alignStart="@+id/textView2" android:onClick="onClickAddName"/> <EditText android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/editText" android:layout_below="@+id/imageButton" android:layou