内容提供程序组件根据请求将数据从一个应用程序提供给其他应用程序.此类请求由ContentResolver类的方法处理.内容提供商可以使用不同的方式来存储其数据,数据可以存储在数据库,文件甚至网络中。
有时需要分享跨应用程序的数据这就是内容提供商变得非常有用的地方。
内容提供商允许您将内容集中在一个地方,并让许多不同的应用程序根据需要访问它.内容提供程序的行为非常类似于数据库,您可以使用insert(),update(),delete()和query()方法查询,编辑其内容以及添加或删除内容.在大多数情况下,此数据存储在 SQlite 数据库中.
内容提供程序是作为 ContentProvider 类的子类实现的,必须实现一组标准的API,使其他应用程序能够执行事务.
- public class My Application extends ContentProvider {
- }
内容URI
要查询内容提供者,请以URI格式指定查询字符串,其格式为:
- < prefix>://< authority>/< data_type>/< id>
以下是URI的各个部分的细节 :
序号 | 描述 |
---|---|
1 | prefix 这始终设置为content:// |
2 | authority 这指定了内容提供商的名称,例如联系人,浏览器等.对于第三方内容提供商,这可能是完全限定的名称,例如 com.it1352.statusprovider |
3 | data_type 这表示此特定提供商提供的数据类型.例如,如果您从 Contacts 内容提供商处获得所有联系人,那么数据路径将是 people ,URI将看起来像 content://联系人/人 |
4 | id 这指定了所请求的特定记录.例如,如果您要在联系人内容提供商中查找联系号码5,则URI将显示为此 content://contacts/people/5 . |
创建内容提供商
这涉及创建自己的内容提供商的一些简单步骤.
首先,您需要创建一个扩展 ContentProviderbaseclass的内容提供程序类.
其次,您需要定义用于访问内容的内容提供商URI地址.
接下来,您需要创建自己的数据库来保留内容.通常,Android使用SQLite数据库和框架需要覆盖 onCreate()方法,该方法将使用SQLite Open Helper方法创建或打开提供程序的数据库.启动应用程序后,将在主应用程序线程上调用每个内容提供程序的 onCreate()处理程序.
接下来,您必须实现Content Provider查询以执行不同的数据库特定操作.
最后使用< provider>在您的活动文件中注册您的Content Provider.标记.
以下是您需要在Content Provider类中覆盖的方法列表:
ContentProvider
onCreate()启动提供程序时调用此方法。
query()此方法接收来自客户端的请求.结果作为Cursor对象返回。
insert()此方法将新记录插入内容提供程序。
delete()此方法从内容提供商处删除现有记录。
update()此方法更新内容提供商的现有记录。
getType() 此方法返回给定URI处数据的MIME类型。
示例
此示例将向您解释如何创建自己的 ContentProvider .因此,让我们按照以下步骤进行操作,类似于我们在创建 Hello World示例 :
步骤 | 描述 |
---|---|
1 | 您将使用Android StudioIDE创建Android应用程序并命名在 com.example.MyApplication 下的我的应用程序,包含空白的活动. |
2 | 修改主活动文件 MainActivity.java 以添加两个新方法 onClickAddName ()和 onClickRetrieveStudents(). |
3 | 在 com.example.MyApplication 包下创建一个名为 StudentsProvider.java 的新java文件,以定义您的实际提供者和相关方法. |
4 | 使用< provider .../在 AndroidManifest.xml 文件中注册您的内容提供商> tag |
5 | 修改 res/layout/activity_main.xml 文件的默认内容,包括一个用于添加学生记录的小GUI. |
6 | 无需更改string.xml.Android工作室来处理string.xml文件. |
7 | 运行应用程序以启动Android模拟器并验证在应用程序中完成更改的结果. |
以下是修改后的主活动文件 src/com.example.MyApplication/MainActivity.java 的.该文件可以包括每个基本生命周期方法.我们添加了两个新方法 onClickAddName()和 onClickRetrieveStudents()来处理用户与应用程序的交互。
- package com.example.MyApplication;
- 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;
- public class MainActivity extends Activity {
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- }
- 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.MyApplication.StudentsProvider";
- 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());
- }
- }
- }
在 com.example.MyApplication下创建新文件StudentsProvider.java 包和以下内容是 src/com.example.MyApplication/StudentsProvider.java :
- package com.example.MyApplication;
- 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.MyApplication.StudentsProvider";
- 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);
- }
- /**
- * Database specific constant declarations
- */
- 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);";
- /**
- * Helper class that actually creates and manages
- * the provider's underlying data repository.
- */
- 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);
- /**
- * Create a write able database which will trigger its
- * creation if it doesn't already exist.
- */
- db = dbHelper.getWritableDatabase();
- return (db == null)? false:true;
- }
- @Override
- public Uri insert(Uri uri, ContentValues values) {
- /**
- * Add a new student record
- */
- long rowID = db.insert( STUDENTS_TABLE_NAME, "", values);
- /**
- * If record is added successfully
- */
- 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:
- }
- if (sortOrder == null || sortOrder == ""){
- /**
- * By default sort on student names
- */
- sortOrder = NAME;
- }
- Cursor c = qb.query(db, projection, selection,
- selectionArgs,null, null, sortOrder);
- /**
- * register to watch a content URI for changes
- */
- 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)){
- /**
- * Get all student records
- */
- case STUDENTS:
- return "vnd.android.cursor.dir/vnd.example.students";
- /**
- * Get a particular student
- */
- case STUDENT_ID:
- return "vnd.android.cursor.item/vnd.example.students";
- default:
- throw new IllegalArgumentException("Unsupported URI: " + uri);
- }
- }
- }
以下是 AndroidManifest.xml 文件的修改内容.在这里,我们添加了< provider .../>标记以包含我们的内容提供者:
- <?xml version="1.0" encoding="utf-8"?>
- <manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.example.MyApplication">
- <application
- android:allowBackup="true"
- android:icon="@mipmap/ic_launcher"
- android:label="@string/app_name"
- android:supportsRtl="true"
- android:theme="@style/AppTheme">
- <activity android:name=".MainActivity">
- <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.MyApplication.StudentsProvider"/>
- </application>
- </manifest>
以下是 res/layout/activity_main.xml 文件的内容 :
- <?xml version="1.0" encoding="utf-8"?>
- <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:paddingBottom="@dimen/activity_vertical_margin"
- android:paddingLeft="@dimen/activity_horizontal_margin"
- android:paddingRight="@dimen/activity_horizontal_margin"
- android:paddingTop="@dimen/activity_vertical_margin"
- tools:context="com.example.MyApplication.MainActivity">
- <TextView
- android:id="@+id/textView1"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="Content provider"
- 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="Tutorials point "
- 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/abc"
- 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="Add Name"
- 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="Name"
- 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="Grade"
- android:textColorHint="@android:color/holo_blue_bright" />
- <Button
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="Retrive student"
- 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 文件的以下内容:
- <?xml version="1.0" encoding="utf-8"?>
- <resources>
- <string name="app_name">My Application</string>
- </resources>
让我们尝试运行我们刚刚创建的修改后的应用程序,这里假设你在进行环境设置时创建了 AVD。要从Android Studio IDE运行应用程序,请打开项目的一个活动文件,然后单击运行工具栏中的图标. Android Studio会在您的AVD上安装应用程序并启动它,如果您的设置和应用程序一切正常,它将显示以下模拟器窗口,请耐心等待,因为它可能需要一段时间:
现在让我们输入学生姓名和成绩,最后点击添加姓名按钮,这将在数据库中添加学生记录,并在底部显示一条消息,显示ContentProvider URI以及数据库中添加的记录号.此操作使用我们的 insert()方法.让我们重复这个过程,在我们的内容提供商的数据库中添加更多的学生。
完成在数据库中添加记录后,现在是时候让ContentProvider回复给我们这些记录了,所以让我们点击获取学生按钮来获取和按照我们 query()方法的实现逐个显示所有记录。
您可以通过提供更新和删除操作来编写活动回调函数在 MainActivity.java 文件中,然后修改用户界面以获得更新和删除操作的按钮,方法与添加和读取操作相同。
通过这种方式,您可以使用现有的Content Provider(如地址簿),或者您可以使用Content Provider概念开发面向数据库的应用程序,您可以在其中执行所有类型的数据库操作如上例中所述,读取,写入,更新和删除等。
转载本站内容时,请务必注明来自W3xue,违者必究。