课程表

Android Studio

Android SDK

工具箱
速查手册

安卓 Content Providers

当前位置:免费教程 » 移动开发 » Android

内容提供程序组件根据请求将数据从一个应用程序提供给其他应用程序.此类请求由ContentResolver类的方法处理.内容提供商可以使用不同的方式来存储其数据,数据可以存储在数据库,文件甚至网络中。

1.jpg

有时需要分享跨应用程序的数据这就是内容提供商变得非常有用的地方。

内容提供商允许您将内容集中在一个地方,并让许多不同的应用程序根据需要访问它.内容提供程序的行为非常类似于数据库,您可以使用insert(),update(),delete()和query()方法查询,编辑其内容以及添加或删除内容.在大多数情况下,此数据存储在 SQlite 数据库中.

内容提供程序是作为 ContentProvider 类的子类实现的,必须实现一组标准的API,使其他应用程序能够执行事务.

  1. public class My Application extends  ContentProvider {
  2. }

内容URI

要查询内容提供者,请以URI格式指定查询字符串,其格式为:

  1. < 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类中覆盖的方法列表:

2.jpg

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 文件中注册您的内容提供商&GT; tag
5修改 res/layout/activity_main.xml 文件的默认内容,包括一个用于添加学生记录的小GUI.
6无需更改string.xml.Android工作室来处理string.xml文件.
7运行应用程序以启动Android模拟器并验证在应用程序中完成更改的结果.

以下是修改后的主活动文件 src/com.example.MyApplication/MainActivity.java 的.该文件可以包括每个基本生命周期方法.我们添加了两个新方法 onClickAddName()和 onClickRetrieveStudents()来处理用户与应用程序的交互。

  1. package com.example.MyApplication;
  2.  
  3. import android.net.Uri;
  4. import android.os.Bundle;
  5. import android.app.Activity;
  6.  
  7. import android.content.ContentValues;
  8. import android.content.CursorLoader;
  9.  
  10. import android.database.Cursor;
  11.  
  12. import android.view.Menu;
  13. import android.view.View;
  14.  
  15. import android.widget.EditText;
  16. import android.widget.Toast;
  17.  
  18. public class MainActivity extends Activity {
  19.  
  20.    @Override
  21.    protected void onCreate(Bundle savedInstanceState) {
  22.       super.onCreate(savedInstanceState);
  23.       setContentView(R.layout.activity_main);
  24.    }
  25.    public void onClickAddName(View view) {
  26.       // Add a new student record
  27.       ContentValues values = new ContentValues();
  28.       values.put(StudentsProvider.NAME,
  29.          ((EditText)findViewById(R.id.editText2)).getText().toString());
  30.  
  31.       values.put(StudentsProvider.GRADE,
  32.          ((EditText)findViewById(R.id.editText3)).getText().toString());
  33.  
  34.       Uri uri = getContentResolver().insert(
  35.          StudentsProvider.CONTENT_URI, values);
  36.  
  37.       Toast.makeText(getBaseContext(),
  38.          uri.toString(), Toast.LENGTH_LONG).show();
  39.    }
  40.    public void onClickRetrieveStudents(View view) {
  41.       // Retrieve student records
  42.       String URL = "content://com.example.MyApplication.StudentsProvider";
  43.  
  44.       Uri students = Uri.parse(URL);
  45.       Cursor c = managedQuery(students, null, null, null, "name");
  46.  
  47.       if (c.moveToFirst()) {
  48.          do{
  49.             Toast.makeText(this,
  50.                c.getString(c.getColumnIndex(StudentsProvider._ID)) +
  51.                   ", " +  c.getString(c.getColumnIndex( StudentsProvider.NAME)) +
  52.                      ", " + c.getString(c.getColumnIndex( StudentsProvider.GRADE)),
  53.             Toast.LENGTH_SHORT).show();
  54.          } while (c.moveToNext());
  55.       }
  56.    }
  57. }

在 com.example.MyApplication下创建新文件StudentsProvider.java 包和以下内容是 src/com.example.MyApplication/StudentsProvider.java :

  1. package com.example.MyApplication;
  2.  
  3. import java.util.HashMap;
  4.  
  5. import android.content.ContentProvider;
  6. import android.content.ContentUris;
  7. import android.content.ContentValues;
  8. import android.content.Context;
  9. import android.content.UriMatcher;
  10.  
  11. import android.database.Cursor;
  12. import android.database.SQLException;
  13.  
  14. import android.database.sqlite.SQLiteDatabase;
  15. import android.database.sqlite.SQLiteOpenHelper;
  16. import android.database.sqlite.SQLiteQueryBuilder;
  17.  
  18. import android.net.Uri;
  19. import android.text.TextUtils;
  20.  
  21. public class StudentsProvider extends ContentProvider {
  22.    static final String PROVIDER_NAME = "com.example.MyApplication.StudentsProvider";
  23.    static final String URL = "content://" + PROVIDER_NAME + "/students";
  24.    static final Uri CONTENT_URI = Uri.parse(URL);
  25.  
  26.    static final String _ID = "_id";
  27.    static final String NAME = "name";
  28.    static final String GRADE = "grade";
  29.  
  30.    private static HashMap<String, String> STUDENTS_PROJECTION_MAP;
  31.  
  32.    static final int STUDENTS = 1;
  33.    static final int STUDENT_ID = 2;
  34.  
  35.    static final UriMatcher uriMatcher;
  36.    static{
  37.       uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
  38.       uriMatcher.addURI(PROVIDER_NAME, "students", STUDENTS);
  39.       uriMatcher.addURI(PROVIDER_NAME, "students/#", STUDENT_ID);
  40.    }
  41.  
  42.    /**
  43.       * Database specific constant declarations
  44.    */
  45.    
  46.    private SQLiteDatabase db;
  47.    static final String DATABASE_NAME = "College";
  48.    static final String STUDENTS_TABLE_NAME = "students";
  49.    static final int DATABASE_VERSION = 1;
  50.    static final String CREATE_DB_TABLE =
  51.       " CREATE TABLE " + STUDENTS_TABLE_NAME +
  52.          " (_id INTEGER PRIMARY KEY AUTOINCREMENT, " +
  53.          " name TEXT NOT NULL, " +
  54.          " grade TEXT NOT NULL);";
  55.  
  56.    /**
  57.       * Helper class that actually creates and manages
  58.       * the provider's underlying data repository.
  59.    */
  60.    
  61.    private static class DatabaseHelper extends SQLiteOpenHelper {
  62.       DatabaseHelper(Context context){
  63.          super(context, DATABASE_NAME, null, DATABASE_VERSION);
  64.       }
  65.  
  66.       @Override
  67.       public void onCreate(SQLiteDatabase db) {
  68.          db.execSQL(CREATE_DB_TABLE);
  69.       }
  70.  
  71.       @Override
  72.       public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
  73.          db.execSQL("DROP TABLE IF EXISTS " +  STUDENTS_TABLE_NAME);
  74.          onCreate(db);
  75.       }
  76.    }
  77.  
  78.    @Override
  79.    public boolean onCreate() {
  80.       Context context = getContext();
  81.       DatabaseHelper dbHelper = new DatabaseHelper(context);
  82.  
  83.       /**
  84.          * Create a write able database which will trigger its
  85.          * creation if it doesn't already exist.
  86.       */
  87.          
  88.       db = dbHelper.getWritableDatabase();
  89.       return (db == null)? false:true;
  90.    }
  91.  
  92.    @Override
  93.    public Uri insert(Uri uri, ContentValues values) {
  94.       /**
  95.          * Add a new student record
  96.       */
  97.       long rowID = db.insert( STUDENTS_TABLE_NAME, "", values);
  98.  
  99.       /**
  100.          * If record is added successfully
  101.       */
  102.       if (rowID > 0) {
  103.          Uri _uri = ContentUris.withAppendedId(CONTENT_URI, rowID);
  104.          getContext().getContentResolver().notifyChange(_uri, null);
  105.          return _uri;
  106.       }
  107.         
  108.       throw new SQLException("Failed to add a record into " + uri);
  109.    }
  110.  
  111.    @Override
  112.    public Cursor query(Uri uri, String[] projection, 
  113.       String selection,String[] selectionArgs, String sortOrder) {
  114.       SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
  115.       qb.setTables(STUDENTS_TABLE_NAME);
  116.  
  117.       switch (uriMatcher.match(uri)) {
  118.          case STUDENTS:
  119.             qb.setProjectionMap(STUDENTS_PROJECTION_MAP);
  120.          break;
  121.  
  122.          case STUDENT_ID:
  123.             qb.appendWhere( _ID + "=" + uri.getPathSegments().get(1));
  124.          break;
  125.          
  126.          default:   
  127.       }
  128.  
  129.       if (sortOrder == null || sortOrder == ""){
  130.          /**
  131.             * By default sort on student names
  132.          */
  133.          sortOrder = NAME;
  134.       }
  135.       
  136.       Cursor c = qb.query(db, projection, selection, 
  137.          selectionArgs,null, null, sortOrder);
  138.       /**
  139.          * register to watch a content URI for changes
  140.       */
  141.       c.setNotificationUri(getContext().getContentResolver(), uri);
  142.       return c;
  143.    }
  144.  
  145.    @Override
  146.    public int delete(Uri uri, String selection, String[] selectionArgs) {
  147.       int count = 0;
  148.       switch (uriMatcher.match(uri)){
  149.          case STUDENTS:
  150.             count = db.delete(STUDENTS_TABLE_NAME, selection, selectionArgs);
  151.          break;
  152.  
  153.          case STUDENT_ID:
  154.             String id = uri.getPathSegments().get(1);
  155.             count = db.delete( STUDENTS_TABLE_NAME, _ID +  " = " + id +
  156.                (!TextUtils.isEmpty(selection) ? 
  157.                AND (" + selection + ')' : ""), selectionArgs);
  158.             break;
  159.          default:
  160.             throw new IllegalArgumentException("Unknown URI " + uri);
  161.       }
  162.  
  163.       getContext().getContentResolver().notifyChange(uri, null);
  164.       return count;
  165.    }
  166.  
  167.    @Override
  168.    public int update(Uri uri, ContentValues values, 
  169.       String selection, String[] selectionArgs) {
  170.       int count = 0;
  171.       switch (uriMatcher.match(uri)) {
  172.          case STUDENTS:
  173.             count = db.update(STUDENTS_TABLE_NAME, values, selection, selectionArgs);
  174.          break;
  175.  
  176.          case STUDENT_ID:
  177.             count = db.update(STUDENTS_TABLE_NAME, values, 
  178.                _ID + " = " + uri.getPathSegments().get(1) +
  179.                (!TextUtils.isEmpty(selection) ? 
  180.                AND (" +selection + ')' : ""), selectionArgs);
  181.             break;
  182.          default:
  183.             throw new IllegalArgumentException("Unknown URI " + uri );
  184.       }
  185.         
  186.       getContext().getContentResolver().notifyChange(uri, null);
  187.       return count;
  188.    }
  189.  
  190.    @Override
  191.    public String getType(Uri uri) {
  192.       switch (uriMatcher.match(uri)){
  193.          /**
  194.             * Get all student records
  195.          */
  196.          case STUDENTS:
  197.             return "vnd.android.cursor.dir/vnd.example.students";
  198.          /**
  199.             * Get a particular student
  200.          */
  201.          case STUDENT_ID:
  202.             return "vnd.android.cursor.item/vnd.example.students";
  203.          default:
  204.             throw new IllegalArgumentException("Unsupported URI: " + uri);
  205.       }
  206.    }
  207. }

以下是 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.example.MyApplication">
  4.  
  5.    <application
  6.       android:allowBackup="true"
  7.       android:icon="@mipmap/ic_launcher"
  8.       android:label="@string/app_name"
  9.       android:supportsRtl="true"
  10.       android:theme="@style/AppTheme">
  11.          <activity android:name=".MainActivity">
  12.             <intent-filter>
  13.                <action android:name="android.intent.action.MAIN" />
  14.                <category android:name="android.intent.category.LAUNCHER" />
  15.             </intent-filter>
  16.          </activity>
  17.         
  18.       <provider android:name="StudentsProvider"
  19.          android:authorities="com.example.MyApplication.StudentsProvider"/>
  20.    </application>
  21. </manifest>

以下是 res/layout/activity_main.xml 文件的内容 :

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3.    xmlns:tools="http://schemas.android.com/tools"
  4.    android:layout_width="match_parent"
  5.    android:layout_height="match_parent"
  6.    android:paddingBottom="@dimen/activity_vertical_margin"
  7.    android:paddingLeft="@dimen/activity_horizontal_margin"
  8.    android:paddingRight="@dimen/activity_horizontal_margin"
  9.    android:paddingTop="@dimen/activity_vertical_margin"
  10.    tools:context="com.example.MyApplication.MainActivity">
  11.  
  12.    <TextView
  13.       android:id="@+id/textView1"
  14.       android:layout_width="wrap_content"
  15.       android:layout_height="wrap_content"
  16.       android:text="Content provider"
  17.       android:layout_alignParentTop="true"
  18.       android:layout_centerHorizontal="true"
  19.       android:textSize="30dp" />
  20.  
  21.    <TextView
  22.       android:id="@+id/textView2"
  23.       android:layout_width="wrap_content"
  24.       android:layout_height="wrap_content"
  25.       android:text="Tutorials point "
  26.       android:textColor="#ff87ff09"
  27.       android:textSize="30dp"
  28.       android:layout_below="@+id/textView1"
  29.       android:layout_centerHorizontal="true" />
  30.  
  31.    <ImageButton
  32.       android:layout_width="wrap_content"
  33.       android:layout_height="wrap_content"
  34.       android:id="@+id/imageButton"
  35.       android:src="@drawable/abc"
  36.       android:layout_below="@+id/textView2"
  37.       android:layout_centerHorizontal="true" />
  38.  
  39.    <Button
  40.       android:layout_width="wrap_content"
  41.       android:layout_height="wrap_content"
  42.       android:id="@+id/button2"
  43.       android:text="Add Name"
  44.       android:layout_below="@+id/editText3"
  45.       android:layout_alignRight="@+id/textView2"
  46.       android:layout_alignEnd="@+id/textView2"
  47.       android:layout_alignLeft="@+id/textView2"
  48.       android:layout_alignStart="@+id/textView2"
  49.       android:onClick="onClickAddName"/>
  50.  
  51.    <EditText
  52.       android:layout_width="wrap_content"
  53.       android:layout_height="wrap_content"
  54.       android:id="@+id/editText"
  55.       android:layout_below="@+id/imageButton"
  56.       android:layout_alignRight="@+id/imageButton"
  57.       android:layout_alignEnd="@+id/imageButton" />
  58.  
  59.    <EditText
  60.       android:layout_width="wrap_content"
  61.       android:layout_height="wrap_content"
  62.       android:id="@+id/editText2"
  63.       android:layout_alignTop="@+id/editText"
  64.       android:layout_alignLeft="@+id/textView1"
  65.       android:layout_alignStart="@+id/textView1"
  66.       android:layout_alignRight="@+id/textView1"
  67.       android:layout_alignEnd="@+id/textView1"
  68.       android:hint="Name"
  69.       android:textColorHint="@android:color/holo_blue_light" />
  70.  
  71.    <EditText
  72.       android:layout_width="wrap_content"
  73.       android:layout_height="wrap_content"
  74.       android:id="@+id/editText3"
  75.       android:layout_below="@+id/editText"
  76.       android:layout_alignLeft="@+id/editText2"
  77.       android:layout_alignStart="@+id/editText2"
  78.       android:layout_alignRight="@+id/editText2"
  79.       android:layout_alignEnd="@+id/editText2"
  80.       android:hint="Grade"
  81.       android:textColorHint="@android:color/holo_blue_bright" />
  82.  
  83.    <Button
  84.       android:layout_width="wrap_content"
  85.       android:layout_height="wrap_content"
  86.       android:text="Retrive student"
  87.       android:id="@+id/button"
  88.       android:layout_below="@+id/button2"
  89.       android:layout_alignRight="@+id/editText3"
  90.       android:layout_alignEnd="@+id/editText3"
  91.       android:layout_alignLeft="@+id/button2"
  92.       android:layout_alignStart="@+id/button2"
  93.       android:onClick="onClickRetrieveStudents"/>
  94. </RelativeLayout>

确保您拥有 res/values/strings.xml 文件的以下内容:

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <resources>
  3.     <string name="app_name">My Application</string>
  4. </resources>

让我们尝试运行我们刚刚创建的修改后的应用程序,这里假设你在进行环境设置时创建了 AVD。要从Android Studio IDE运行应用程序,请打开项目的一个活动文件,然后单击运行工具栏中的图标. Android Studio会在您的AVD上安装应用程序并启动它,如果您的设置和应用程序一切正常,它将显示以下模拟器窗口,请耐心等待,因为它可能需要一段时间:

3.jpg

现在让我们输入学生姓名和成绩,最后点击添加姓名按钮,这将在数据库中添加学生记录,并在底部显示一条消息,显示ContentProvider URI以及数据库中添加的记录号.此操作使用我们的 insert()方法.让我们重复这个过程,在我们的内容提供商的数据库中添加更多的学生。

4.jpg

完成在数据库中添加记录后,现在是时候让ContentProvider回复给我们这些记录了,所以让我们点击获取学生按钮来获取和按照我们 query()方法的实现逐个显示所有记录。

您可以通过提供更新和删除操作来编写活动回调函数在 MainActivity.java 文件中,然后修改用户界面以获得更新和删除操作的按钮,方法与添加和读取操作相同。

通过这种方式,您可以使用现有的Content Provider(如地址簿),或者您可以使用Content Provider概念开发面向数据库的应用程序,您可以在其中执行所有类型的数据库操作如上例中所述,读取,写入,更新和删除等。

转载本站内容时,请务必注明来自W3xue,违者必究。
 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号