Android 內(nèi)容提供者(Content Provider)

2023-05-09 11:09 更新

Android 內(nèi)容提供者(Content Provider)

內(nèi)容提供者組件通過請求從一個應(yīng)用程序向其他的應(yīng)用程序提供數(shù)據(jù)。這些請求由類 ContentResolver 的方法來處理。內(nèi)容提供者可以使用不同的方式來存儲數(shù)據(jù)。數(shù)據(jù)可以被存放在數(shù)據(jù)庫,文件,甚至是網(wǎng)絡(luò)。

有時候需要在應(yīng)用程序之間共享數(shù)據(jù)。這時內(nèi)容提供者變得非常有用。

內(nèi)容提供者可以讓內(nèi)容集中,必要時可以有多個不同的應(yīng)用程序來訪問。內(nèi)容提供者的行為和數(shù)據(jù)庫很像。你可以查詢,編輯它的內(nèi)容,使用 insert(), update(), delete() 和 query() 來添加或者刪除內(nèi)容。多數(shù)情況下數(shù)據(jù)被存儲在 SQLite 數(shù)據(jù)庫。

內(nèi)容提供者被實現(xiàn)為類 ContentProvider 類的子類。需要實現(xiàn)一系列標(biāo)準(zhǔn)的 API,以便其他的應(yīng)用程序來執(zhí)行事務(wù)。

public class MyApplication extends  ContentProvider {

}

內(nèi)容URI

要查詢內(nèi)容提供者,你需要以如下格式的URI的形式來指定查詢字符串:

<prefix>://<authority>/<data_type>/<id>

以下是URI中各部分的具體說明:

部分說明
prefix前綴:一直被設(shè)置為content://
authority授權(quán):指定內(nèi)容提供者的名稱,例如聯(lián)系人,瀏覽器等。第三方的內(nèi)容提供者可以是全名,如:cn.programmer.statusprovider
data_type數(shù)據(jù)類型:這個表明這個特殊的內(nèi)容提供者中的數(shù)據(jù)的類型。例如:你要通過內(nèi)容提供者Contacts來獲取所有的通訊錄,數(shù)據(jù)路徑是people,那么URI將是下面這樣:content://contacts/people
id這個指定特定的請求記錄。例如:你在內(nèi)容提供者Contacts中查找聯(lián)系人的ID號為5,那么URI看起來是這樣:content://contacts/people/5

創(chuàng)建內(nèi)容提供者

這里描述創(chuàng)建自己的內(nèi)容提供者的簡單步驟。

  • 首先,你需要繼承類 ContentProviderbase 來創(chuàng)建一個內(nèi)容提供者類。
  • 其次,你需要定義用于訪問內(nèi)容的你的內(nèi)容提供者URI地址。
  • 接下來,你需要創(chuàng)建數(shù)據(jù)庫來保存內(nèi)容。通常,Android 使用 SQLite 數(shù)據(jù)庫,并在框架中重寫 onCreate() 方法來使用 SQLiteOpenHelper 的方法創(chuàng)建或者打開提供者的數(shù)據(jù)庫。當(dāng)你的應(yīng)用程序被啟動,它的每個內(nèi)容提供者的 onCreate() 方法將在應(yīng)用程序主線程中被調(diào)用。
  • 最后,使用<provider.../>標(biāo)簽在 AndroidManifest.xml 中注冊內(nèi)容提供者。

以下是讓你的內(nèi)容提供者正常工作,你需要在類 ContentProvider 中重寫的一些方法:

  • onCreate():當(dāng)提供者被啟動時調(diào)用。
  • query():該方法從客戶端接受請求。結(jié)果是返回指針(Cursor)對象。
  • insert():該方法向內(nèi)容提供者插入新的記錄。
  • delete():該方法從內(nèi)容提供者中刪除已存在的記錄。
  • update():該方法更新內(nèi)容提供者中已存在的記錄。
  • getType():該方法為給定的URI返回元數(shù)據(jù)類型。

實例

該實例解釋如何創(chuàng)建自己的內(nèi)容提供者。讓我們按照下面的步驟:

步驟描述
1使用 Android Studio 創(chuàng)建 Android 應(yīng)用程序并命名為 Content Provider,在包cn.uprogrammer.contentprovider 下,并建立空活動。
2修改主要活動文件 MainActivity.java 來添加兩個新的方法 onClickAddName() 和 onClickRetrieveStudents()。
3在包 cn.uprogrammer.contentprovider 下創(chuàng)建新的 Java 文件 StudentsProvider.java 來定義實際的提供者,并關(guān)聯(lián)方法。
4使用<provider.../>標(biāo)簽在 AndroidManifest.xml 中注冊內(nèi)容提供者。
5修改 res/layout/activity_main.xml 文件的默認(rèn)內(nèi)容來包含添加學(xué)生記錄的簡單界面。
6無需修改 strings.xml,Android Studio 會注意 strings.xml 文件。
7啟動 Android 模擬器來運行應(yīng)用程序,并驗證應(yīng)用程序所做改變的結(jié)果。

下面是修改的主要活動文件 src/cn.uprogrammer.contentprovider/MainActivity.java 的內(nèi)容。該文件包含每個基礎(chǔ)的生命周期方法。我們添加了兩個新的方法,onClickAddName() 和 onClickRetrieveStudents() 來讓應(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());
        }
    }
}

在包cn.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ù)庫特定常量聲明
     */
    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)建一個可寫的數(shù)據(jù)庫。
         */
        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);

        /**
         * 注冊內(nèi)容URI變化的監(jiān)聽器
         */
        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";

            /**
             * 獲取一個特定的學(xué)生
             */
            case STUDENT_ID:
                return "vnd.android.cursor.item/vnd.example.students";

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

以下是修改后的AndroidManifest.xml文件。這里添加了<provider.../>標(biāo)簽來包含我們的內(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)容提供者實例"
        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:layout_alignRight="@+id/imageButton"
        android:layout_alignEnd="@+id/imageButton" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/editText2"
        android:layout_alignTop="@+id/editText"
        android:layout_alignLeft="@+id/textView1"
        android:layout_alignStart="@+id/textView1"
        android:layout_alignRight="@+id/textView1"
        android:layout_alignEnd="@+id/textView1"
        android:hint="姓名"
        android:textColorHint="@android:color/holo_blue_light" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/editText3"
        android:layout_below="@+id/editText"
        android:layout_alignLeft="@+id/editText2"
        android:layout_alignStart="@+id/editText2"
        android:layout_alignRight="@+id/editText2"
        android:layout_alignEnd="@+id/editText2"
        android:hint="年級"
        android:textColorHint="@android:color/holo_blue_bright" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="查詢"
        android:id="@+id/button"
        android:layout_below="@+id/button2"
        android:layout_alignRight="@+id/editText3"
        android:layout_alignEnd="@+id/editText3"
        android:layout_alignLeft="@+id/button2"
        android:layout_alignStart="@+id/button2"
        android:onClick="onClickRetrieveStudents"/>

</RelativeLayout>

確保res/values/strings.xml文件中有以下內(nèi)容:

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

    <string name="app_name">Content Provider</string>
    <string name="action_settings">Settings</string>

</resources>

讓我們運行剛剛修改的 Content Provider 應(yīng)用程序。我假設(shè)你已經(jīng)在安裝環(huán)境時創(chuàng)建了 AVD。打開你的項目中的活動文件,點擊工具欄中的圖標(biāo)來在 Android Studio 中運行應(yīng)用程序。Android Studio 在 AVD 上安裝應(yīng)用程序并啟動它。如果一切順利,將在模擬器窗口上顯示如下:

輸入姓名和年級,并點擊"添加"按鈕,這將在數(shù)據(jù)中添加一條學(xué)生記錄,并在底部刪除一條信息。信息內(nèi)容顯示包含添加進數(shù)據(jù)庫的記錄數(shù)的內(nèi)容提供者URI。這個操作使用了insert()方法。重復(fù)這個過程在我們的內(nèi)容提供者的數(shù)據(jù)庫中添加更多的學(xué)生。

一旦你完成數(shù)據(jù)庫記錄的添加,是時候向內(nèi)容提供者要求給回這些記錄。點擊"查詢"按鈕,這將通過實現(xiàn)的 query() 方法來獲取并顯示所有的數(shù)據(jù)記錄。

你可以在 MainActivity.java 中提供回調(diào)方法,來編寫更新和刪除的操作,并修改用戶界面來添加更新和刪除操作。

你可以通過這種方式使用已有的內(nèi)容提供者,如通訊錄。你也可以通過這種方式來開發(fā)一個優(yōu)秀的面向數(shù)據(jù)庫的應(yīng)用,你可以像上面介紹的實例那樣來執(zhí)行所有的數(shù)據(jù)庫操作,如讀、寫、更新和刪除。


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號