Android 内容提供者(Content Provider)

[复制链接]

Android 内容提供者(Content Provider)

发表于 2021-12-28 13:51:18 只看大图 阅读模式 倒序浏览
1117 0 查看全部
  内容提供者组件通过请求从一个应用程序向其他的应用程序提供数据。这些请求由类 ContentResolver 的方法来处理。内容提供者可以使用不同的方式来存储数据。数据可以被存放在数据库,文件,甚至是网络。
content.jpg
  有时候需要在应用程序之间共享数据。这时内容提供者变得非常有用。
  内容提供者可以让内容集中,必要时可以有多个不同的应用程序来访问。内容提供者的行为和数据库很像。你可以查询,编辑它的内容,使用 insert(), update(), delete() 和 query() 来添加或者删除内容。多数情况下数据被存储在 SQLite 数据库。
  内容提供者被实现为类 ContentProvider 类的子类。需要实现一系列标准的 API,以便其他的应用程序来执行事务。
  1. public class MyApplication extends  ContentProvider {

  2. }
复制代码
内容URI  要查询内容提供者,你需要以如下格式的URI的形式来指定查询字符串:
  1. ‹prefix>://‹authority>/‹data_type>/‹id>
复制代码
  以下是URI中各部分的具体说明:
部分说明
prefix前缀:一直被设置为content://
authority授权:指定内容提供者的名称,例如联系人,浏览器等。第三方的内容提供者可以是全名,如:cn.programmer.statusprovider
data_type数据类型:这个表明这个特殊的内容提供者中的数据的类型。例如:你要通过内容提供者Contacts来获取所有的通讯录,数据路径是people,那么URI将是下面这样:content://contacts/people
id这个指定特定的请求记录。例如:你在内容提供者Contacts中查找联系人的ID号为5,那么URI看起来是这样:content://contacts/people/5创建内容提供者  这里描述创建自己的内容提供者的简单步骤。
  • 首先,你需要继承类 ContentProviderbase 来创建一个内容提供者类。
  • 其次,你需要定义用于访问内容的你的内容提供者URI地址。
  • 接下来,你需要创建数据库来保存内容。通常,Android 使用 SQLite 数据库,并在框架中重写 onCreate() 方法来使用 SQLiteOpenHelper 的方法创建或者打开提供者的数据库。当你的应用程序被启动,它的每个内容提供者的 onCreate() 方法将在应用程序主线程中被调用。
  • 最后,使用‹provider.../>标签在 AndroidManifest.xml 中注册内容提供者。
  以下是让你的内容提供者正常工作,你需要在类 ContentProvider 中重写的一些方法:
content1.jpg
  • onCreate():当提供者被启动时调用。
  • query():该方法从客户端接受请求。结果是返回指针(Cursor)对象。
  • insert():该方法向内容提供者插入新的记录。
  • delete():该方法从内容提供者中删除已存在的记录。
  • update():该方法更新内容提供者中已存在的记录。
  • getType():该方法为给定的URI返回元数据类型。
实例  该实例解释如何创建自己的内容提供者。让我们按照下面的步骤:
步骤描述
1使用 Android Studio 创建 Android 应用程序并命名为 Content Provider,在包com.runoob.contentprovider 下,并建立空活动。
2修改主要活动文件 MainActivity.java 来添加两个新的方法 onClickAddName() 和 onClickRetrieveStudents()。
3在包 com.runoob.contentprovider 下创建新的 Java 文件 StudentsProvider.java 来定义实际的提供者,并关联方法。
4使用‹provider.../>标签在 AndroidManifest.xml 中注册内容提供者。
5修改 res/layout/activity_main.xml 文件的默认内容来包含添加学生记录的简单界面。
6无需修改 strings.xml,Android Studio 会注意 strings.xml 文件。
7启动 Android 模拟器来运行应用程序,并验证应用程序所做改变的结果。  下面是修改的主要活动文件 src/com.runoob.contentprovider/MainActivity.java 的内容。该文件包含每个基础的生命周期方法。我们添加了两个新的方法,onClickAddName() 和 onClickRetrieveStudents() 来让应用程序处理用户交互。
  1. package com.runoob.contentprovider;

  2. import android.net.Uri;
  3. import android.os.Bundle;
  4. import android.app.Activity;
  5. import android.content.ContentValues;
  6. import android.content.CursorLoader;
  7. import android.database.Cursor;
  8. import android.view.Menu;
  9. import android.view.View;
  10. import android.widget.EditText;
  11. import android.widget.Toast;
  12. import com.runoob.contentprovider.R;

  13. public class MainActivity extends Activity {

  14.     @Override
  15.     protected void onCreate(Bundle savedInstanceState) {
  16.         super.onCreate(savedInstanceState);
  17.         setContentView(R.layout.activity_main);
  18.     }

  19.     @Override
  20.     public boolean onCreateOptionsMenu(Menu menu) {
  21.         getMenuInflater().inflate(R.menu.menu_main, menu);
  22.         return true;
  23.     }

  24.     public void onClickAddName(View view) {
  25.         // Add a new student record
  26.         ContentValues values = new ContentValues();

  27.         values.put(StudentsProvider.NAME,
  28.                 ((EditText)findViewById(R.id.editText2)).getText().toString());

  29.         values.put(StudentsProvider.GRADE,
  30.                 ((EditText)findViewById(R.id.editText3)).getText().toString());

  31.         Uri uri = getContentResolver().insert(
  32.                 StudentsProvider.CONTENT_URI, values);

  33.         Toast.makeText(getBaseContext(),
  34.                 uri.toString(), Toast.LENGTH_LONG).show();
  35.     }

  36.     public void onClickRetrieveStudents(View view) {

  37.         // Retrieve student records
  38.         String URL = "content://com.example.provider.College/students";

  39.         Uri students = Uri.parse(URL);
  40.         Cursor c = managedQuery(students, null, null, null, "name");

  41.         if (c.moveToFirst()) {
  42.             do{
  43.                 Toast.makeText(this,
  44.                         c.getString(c.getColumnIndex(StudentsProvider._ID)) +
  45.                                 ", " +  c.getString(c.getColumnIndex( StudentsProvider.NAME)) +
  46.                                 ", " + c.getString(c.getColumnIndex( StudentsProvider.GRADE)),
  47.                         Toast.LENGTH_SHORT).show();
  48.             } while (c.moveToNext());
  49.         }
  50.     }
  51. }
复制代码
  在包com.runoob.contentprovider下创建新的文件StudentsProvider.java。以下是src/com.runoob.contentprovider/StudentsProvider.java的内容。

  1. package com.runoob.contentprovider;

  2. import java.util.HashMap;

  3. import android.content.ContentProvider;
  4. import android.content.ContentUris;
  5. import android.content.ContentValues;
  6. import android.content.Context;
  7. import android.content.UriMatcher;

  8. import android.database.Cursor;
  9. import android.database.SQLException;
  10. import android.database.sqlite.SQLiteDatabase;
  11. import android.database.sqlite.SQLiteOpenHelper;
  12. import android.database.sqlite.SQLiteQueryBuilder;

  13. import android.net.Uri;
  14. import android.text.TextUtils;

  15. public class StudentsProvider extends ContentProvider {

  16.     static final String PROVIDER_NAME = "com.example.provider.College";
  17.     static final String URL = "content://" + PROVIDER_NAME + "/students";
  18.     static final Uri CONTENT_URI = Uri.parse(URL);

  19.     static final String _ID = "_id";
  20.     static final String NAME = "name";
  21.     static final String GRADE = "grade";

  22.     private static HashMap‹String, String> STUDENTS_PROJECTION_MAP;

  23.     static final int STUDENTS = 1;
  24.     static final int STUDENT_ID = 2;

  25.     static final UriMatcher uriMatcher;
  26.     static{
  27.         uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
  28.         uriMatcher.addURI(PROVIDER_NAME, "students", STUDENTS);
  29.         uriMatcher.addURI(PROVIDER_NAME, "students/#", STUDENT_ID);
  30.     }

  31.     /**
  32.      * 数据库特定常量声明
  33.      */
  34.     private SQLiteDatabase db;
  35.     static final String DATABASE_NAME = "College";
  36.     static final String STUDENTS_TABLE_NAME = "students";
  37.     static final int DATABASE_VERSION = 1;
  38.     static final String CREATE_DB_TABLE =
  39.             " CREATE TABLE " + STUDENTS_TABLE_NAME +
  40.                     " (_id INTEGER PRIMARY KEY AUTOINCREMENT, " +
  41.                     " name TEXT NOT NULL, " +
  42.                     " grade TEXT NOT NULL);";

  43.     /**
  44.      * 创建和管理提供者内部数据源的帮助类.
  45.      */
  46.     private static class DatabaseHelper extends SQLiteOpenHelper {
  47.         DatabaseHelper(Context context){
  48.             super(context, DATABASE_NAME, null, DATABASE_VERSION);
  49.         }

  50.         @Override
  51.         public void onCreate(SQLiteDatabase db)
  52.         {
  53.             db.execSQL(CREATE_DB_TABLE);
  54.         }

  55.         @Override
  56.         public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
  57.             db.execSQL("DROP TABLE IF EXISTS " +  STUDENTS_TABLE_NAME);
  58.             onCreate(db);
  59.         }
  60.     }

  61.     @Override
  62.     public boolean onCreate() {
  63.         Context context = getContext();
  64.         DatabaseHelper dbHelper = new DatabaseHelper(context);

  65.         /**
  66.          * 如果不存在,则创建一个可写的数据库。
  67.          */
  68.         db = dbHelper.getWritableDatabase();
  69.         return (db == null)? false:true;
  70.     }

  71.     @Override
  72.     public Uri insert(Uri uri, ContentValues values) {
  73.         /**
  74.          * 添加新学生记录
  75.          */
  76.         long rowID = db.insert( STUDENTS_TABLE_NAME, "", values);

  77.         /**
  78.          * 如果记录添加成功
  79.          */

  80.         if (rowID > 0)
  81.         {
  82.             Uri _uri = ContentUris.withAppendedId(CONTENT_URI, rowID);
  83.             getContext().getContentResolver().notifyChange(_uri, null);
  84.             return _uri;
  85.         }
  86.         throw new SQLException("Failed to add a record into " + uri);
  87.     }

  88.     @Override
  89.     public Cursor query(Uri uri, String[] projection, String selection,String[] selectionArgs, String sortOrder) {
  90.         SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
  91.         qb.setTables(STUDENTS_TABLE_NAME);

  92.         switch (uriMatcher.match(uri)) {
  93.             case STUDENTS:
  94.                 qb.setProjectionMap(STUDENTS_PROJECTION_MAP);
  95.                 break;

  96.             case STUDENT_ID:
  97.                 qb.appendWhere( _ID + "=" + uri.getPathSegments().get(1));
  98.                 break;

  99.             default:
  100.                 throw new IllegalArgumentException("Unknown URI " + uri);
  101.         }

  102.         if (sortOrder == null || sortOrder == ""){
  103.             /**
  104.              * 默认按照学生姓名排序
  105.              */
  106.             sortOrder = NAME;
  107.         }
  108.         Cursor c = qb.query(db, projection, selection, selectionArgs,null, null, sortOrder);

  109.         /**
  110.          * 注册内容URI变化的监听器
  111.          */
  112.         c.setNotificationUri(getContext().getContentResolver(), uri);
  113.         return c;
  114.     }

  115.     @Override
  116.     public int delete(Uri uri, String selection, String[] selectionArgs) {
  117.         int count = 0;

  118.         switch (uriMatcher.match(uri)){
  119.             case STUDENTS:
  120.                 count = db.delete(STUDENTS_TABLE_NAME, selection, selectionArgs);
  121.                 break;

  122.             case STUDENT_ID:
  123.                 String id = uri.getPathSegments().get(1);
  124.                 count = db.delete( STUDENTS_TABLE_NAME, _ID +  " = " + id +
  125.                         (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : ""), selectionArgs);
  126.                 break;

  127.             default:
  128.                 throw new IllegalArgumentException("Unknown URI " + uri);
  129.         }

  130.         getContext().getContentResolver().notifyChange(uri, null);
  131.         return count;
  132.     }

  133.     @Override
  134.     public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
  135.         int count = 0;

  136.         switch (uriMatcher.match(uri)){
  137.             case STUDENTS:
  138.                 count = db.update(STUDENTS_TABLE_NAME, values, selection, selectionArgs);
  139.                 break;

  140.             case STUDENT_ID:
  141.                 count = db.update(STUDENTS_TABLE_NAME, values, _ID + " = " + uri.getPathSegments().get(1) +
  142.                         (!TextUtils.isEmpty(selection) ? " AND (" +selection + ')' : ""), selectionArgs);
  143.                 break;

  144.             default:
  145.                 throw new IllegalArgumentException("Unknown URI " + uri );
  146.         }
  147.         getContext().getContentResolver().notifyChange(uri, null);
  148.         return count;
  149.     }

  150.     @Override
  151.     public String getType(Uri uri) {
  152.         switch (uriMatcher.match(uri)){
  153.             /**
  154.              * 获取所有学生记录
  155.              */
  156.             case STUDENTS:
  157.                 return "vnd.android.cursor.dir/vnd.example.students";

  158.             /**
  159.              * 获取一个特定的学生
  160.              */
  161.             case STUDENT_ID:
  162.                 return "vnd.android.cursor.item/vnd.example.students";

  163.             default:
  164.                 throw new IllegalArgumentException("Unsupported URI: " + uri);
  165.         }
  166.     }
  167. }
复制代码
  以下是修改后的AndroidManifest.xml文件。这里添加了‹provider.../>标签来包含我们的内容提供者:

  1. ‹?xml version="1.0" encoding="utf-8"?>
  2. ‹manifest xmlns:android="http://schemas.android.com/apk/res/android"
  3.     package="com.runoob.contentprovider"
  4.     android:versionCode="1"
  5.     android:versionName="1.0" >

  6.     ‹uses-sdk
  7.         android:minSdkVersion="8"
  8.         android:targetSdkVersion="22" />

  9.     ‹application
  10.         android:allowBackup="true"
  11.         android:icon="@drawable/ic_launcher"
  12.         android:label="@string/app_name"
  13.         android:theme="@style/AppTheme" >

  14.         ‹activity
  15.             android:name="com.runoob.contentprovider.MainActivity"
  16.             android:label="@string/app_name" >

  17.             ‹intent-filter>
  18.                 ‹action android:name="android.intent.action.MAIN" />
  19.                 ‹category android:name="android.intent.category.LAUNCHER" />
  20.             ‹/intent-filter>

  21.         ‹/activity>

  22.         ‹provider android:name="StudentsProvider"
  23.             android:authorities="com.example.provider.College" >
  24.         ‹/provider>

  25.     ‹/application>

  26. ‹/manifest>
复制代码
  下面是res/layout/activity_main.xml文件的内容:

  1. ‹RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  2.     xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
  3.     android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
  4.     android:paddingRight="@dimen/activity_horizontal_margin"
  5.     android:paddingTop="@dimen/activity_vertical_margin"
  6.     android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

  7.     ‹TextView
  8.         android:id="@+id/textView1"
  9.         android:layout_width="wrap_content"
  10.         android:layout_height="wrap_content"
  11.         android:text="内容提供者实例"
  12.         android:layout_alignParentTop="true"
  13.         android:layout_centerHorizontal="true"
  14.         android:textSize="30dp" />

  15.     ‹TextView
  16.         android:id="@+id/textView2"
  17.         android:layout_width="wrap_content"
  18.         android:layout_height="wrap_content"
  19.         android:text="www.runoob.com"
  20.         android:textColor="#ff87ff09"
  21.         android:textSize="30dp"
  22.         android:layout_below="@+id/textView1"
  23.         android:layout_centerHorizontal="true" />

  24.     ‹ImageButton
  25.         android:layout_width="wrap_content"
  26.         android:layout_height="wrap_content"
  27.         android:id="@+id/imageButton"
  28.         android:src="@drawable/ic_launcher"
  29.         android:layout_below="@+id/textView2"
  30.         android:layout_centerHorizontal="true" />

  31.     ‹Button
  32.         android:layout_width="wrap_content"
  33.         android:layout_height="wrap_content"
  34.         android:id="@+id/button2"
  35.         android:text="添加"
  36.         android:layout_below="@+id/editText3"
  37.         android:layout_alignRight="@+id/textView2"
  38.         android:layout_alignEnd="@+id/textView2"
  39.         android:layout_alignLeft="@+id/textView2"
  40.         android:layout_alignStart="@+id/textView2"
  41.         android:onClick="onClickAddName"/>

  42.     ‹EditText
  43.         android:layout_width="wrap_content"
  44.         android:layout_height="wrap_content"
  45.         android:id="@+id/editText"
  46.         android:layout_below="@+id/imageButton"
  47.         android:layout_alignRight="@+id/imageButton"
  48.         android:layout_alignEnd="@+id/imageButton" />

  49.     ‹EditText
  50.         android:layout_width="wrap_content"
  51.         android:layout_height="wrap_content"
  52.         android:id="@+id/editText2"
  53.         android:layout_alignTop="@+id/editText"
  54.         android:layout_alignLeft="@+id/textView1"
  55.         android:layout_alignStart="@+id/textView1"
  56.         android:layout_alignRight="@+id/textView1"
  57.         android:layout_alignEnd="@+id/textView1"
  58.         android:hint="姓名"
  59.         android:textColorHint="@android:color/holo_blue_light" />

  60.     ‹EditText
  61.         android:layout_width="wrap_content"
  62.         android:layout_height="wrap_content"
  63.         android:id="@+id/editText3"
  64.         android:layout_below="@+id/editText"
  65.         android:layout_alignLeft="@+id/editText2"
  66.         android:layout_alignStart="@+id/editText2"
  67.         android:layout_alignRight="@+id/editText2"
  68.         android:layout_alignEnd="@+id/editText2"
  69.         android:hint="年级"
  70.         android:textColorHint="@android:color/holo_blue_bright" />

  71.     ‹Button
  72.         android:layout_width="wrap_content"
  73.         android:layout_height="wrap_content"
  74.         android:text="查询"
  75.         android:id="@+id/button"
  76.         android:layout_below="@+id/button2"
  77.         android:layout_alignRight="@+id/editText3"
  78.         android:layout_alignEnd="@+id/editText3"
  79.         android:layout_alignLeft="@+id/button2"
  80.         android:layout_alignStart="@+id/button2"
  81.         android:onClick="onClickRetrieveStudents"/>

  82. ‹/RelativeLayout>
复制代码
  确保res/values/strings.xml文件中有以下内容:

  1. ‹?xml version="1.0" encoding="utf-8"?>
  2. ‹resources>

  3.     ‹string name="app_name">Content Provider‹/string>
  4.     ‹string name="action_settings">Settings‹/string>

  5. ‹/resources>
复制代码
  让我们运行刚刚修改的 Content Provider 应用程序。我假设你已经在安装环境时创建了 AVD。打开你的项目中的活动文件,点击工具栏中的 eclipse_run.png 图标来在 Android Studio 中运行应用程序。Android Studio 在 AVD 上安装应用程序并启动它。如果一切顺利,将在模拟器窗口上显示如下:
android_content_provider_1-1.png
  输入姓名和年级,并点击"添加"按钮,这将在数据中添加一条学生记录,并在底部删除一条信息。信息内容显示包含添加进数据库的记录数的内容提供者URI。这个操作使用了insert()方法。重复这个过程在我们的内容提供者的数据库中添加更多的学生。
android_content_provider_2-1.png
  一旦你完成数据库记录的添加,是时候向内容提供者要求给回这些记录。点击"查询"按钮,这将通过实现的 query() 方法来获取并显示所有的数据记录。
  你可以在 MainActivity.java 中提供回调方法,来编写更新和删除的操作,并修改用户界面来添加更新和删除操作。
  你可以通过这种方式使用已有的内容提供者,如通讯录。你也可以通过这种方式来开发一个优秀的面向数据库的应用,你可以像上面介绍的实例那样来执行素有的数据库操作,如读、写、更新和删除。

来源:菜鸟教程
回复

使用道具 举报

游客~
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Archiver|手机版|小黑屋|极客同行 ( 蜀ICP备17009389号-1 )

© 2013-2016 Comsenz Inc. Powered by Discuz! X3.4