首页 > 系统 > Android > 正文

Android开发教程之ContentProvider数据存储

2019-12-12 04:13:24
字体:
来源:转载
供稿:网友

一、ContentProvider保存数据介绍

一个程序可以通过实现一个ContentProvider的抽象接口将自己的数据完全暴露出去,而且ContentProvider是以类似数据库中表的方式将数据暴露的。那么外界获取其提供的数据,也就应该与从数据库中获取数据的操作基本一样,只不过是采用URL来表示外界需要访问的“数据库”。

ContentProvider提供了一种多应用间数据共享的方式。

ContentProvider是个实现了一组用于提供其他应用程序存取数据的标准方法的类。应用程序可以在ContentProvider中执行如下操作:查询数据、修改数据、添加数据、删除数据。

标准的ContentProvider:Android提供了一些已经在系统中实现的标准ContentProvider,比如联系人信息,图片库等等,可以用这些ContentProvider来访问设备上存储的联系人信息、图片等等。

在ContentProvider中使用的查询字符串有别于标准的SQL查询,很多诸如select、add、delete、modify等操作都使用一种特殊的URL进行,这种URL由3部分组成,“content://”,代表数据的路径和一个可选的表示数据的ID。

content://media/internal/images 这个URL将返回设备上存储的所有图片

content://contacts/people/ 这个URL将返回设备上的所有联系人信息

content://contacts/people/45 这个URL返回单个结果(联系人信息中ID为45的联系人记录)

 如果想要存储字节型数据,比如位图文件等,那保存该数据的数据列其实是一个表示实际保存保存文件的URL字符串,客户端通过它来读取对应的文件数据,处理这种数据类型的ContentProvider需要实现一个名为_data的字段,_data字段列出了该文件在Android文件系统上的精确路径。这个字段不仅是供客户端使用,而且也可以供ContentResolver使用。客户端可以调用ContentResolver.openOutputStream()方法来处理该URL指向的文件资源,如果是ContentResolver本身的话,由于其持有的权限比客户端要高,所以它能直接访问该数据文件。

二、使用方法

大多数ContentProvider使用Android文件系统或者SQLite数据库来保持数据,但是也可以以任何方式来存储。本例用SQLite数据库来保持数据。

1.创建一个接口,定义了一个名为CONTENT_URL,并且是public static final的Uri类型的类变量,必须为其指定一个唯一的字符串值,最好的方案是类的全称,和数据列的名称。

public interface IProivderMetaData {  public static final String AUTHORITY = "com.zhangmiao.datastoragedemo";  public static final String DB_NAME = "book.db";  public static final int VERSION = 1;  public interface BookTableMetaData extends BaseColumns {    public static final String TABLE_NAME = "book";    public static final Uri CONTENT_URI = Uri.parse("content://"            + AUTHORITY + "/" + TABLE_NAME);    public static final String BOOK_ID = "_id";    public static final String BOOK_NAME = "name";    public static final String BOOK_PUBLISHER = "publisher";    public static final String SORT_ORDER = "_id desc";    public static final String CONTENT_LIST = "vnd.android.cursor.dir/vnd.bookprovider.book";    public static final String CONTENT_ITEM = "vnd.android.cursor.item/vnd.bookprovider.book";  }}

2.实现SQLiteOpenHelper

public class ContentProviderDBHelper extends SQLiteOpenHelper implements IProivderMetaData {  private static final String TAG = "ContentProviderDBHelper";  public ContentProviderDBHelper(Context context) {    super(context, DB_NAME, null, VERSION);  }  @Override  public void onCreate(SQLiteDatabase db) {    ...  }  @Override  public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {    ...  }}

3.创建一个继承了ContentProvider父类的类

public class ContentProviderDBHelper extends SQLiteOpenHelper implements IProivderMetaData {  public ContentProviderDBHelper(Context context) {    super(context, DB_NAME, null, VERSION);  }  @Override  public void onCreate(SQLiteDatabase db) {    ...  }  @Override  public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {    ...  }}

4.在AndroidManifest.xml中使用标签来设置调用ContentProvider。

<provider   android:authorities="com.zhangmiao.datastoragedemo"   android:name=".BookContentProvider"/>

5.增加数据

mContentResolver = getContentResolver();String[] bookNames = new String[]{"Chinese", "Math", "English", "Sports"};String[] bookPublishers = new String[]{"XinHua", "GongXin", "DianZi", "YouDian"};for (int i = 0; i < bookNames.length; i++) {  ContentValues values = new ContentValues();  values.put(IProivderMetaData.BookTableMetaData.BOOK_NAME, bookNames[i]);  values.put(IProivderMetaData.BookTableMetaData.BOOK_PUBLISHER, bookPublishers[i]);  mContentResolver.insert(IProivderMetaData.BookTableMetaData.CONTENT_URI, values);}

6.删除数据

String bookId = "1";if (!"".equals(bookId)) {   ContentValues values1 = new ContentValues();   values1.put(IProivderMetaData.BookTableMetaData.BOOK_ID,bookId);   mContentResolver.delete(Uri.withAppendedPath(                  IProivderMetaData.BookTableMetaData.CONTENT_URI,                  bookId),                 "_id = ?",              new String[]{bookId}   );} else {  mContentResolver.delete(       IProivderMetaData.BookTableMetaData.CONTENT_URI,       null,       null  );}

7.查询数据

Cursor cursor = mContentResolver.query(IProivderMetaData.BookTableMetaData.CONTENT_URI,            null, null, null, null);String text = "";if (cursor != null) {  while (cursor.moveToNext()) {    String bookIdText =cursor.getString(cursor.getColumnIndex(IProivderMetaData.BookTableMetaData.BOOK_ID));    String bookNameText =cursor.getString(cursor.getColumnIndex(IProivderMetaData.BookTableMetaData.BOOK_NAME));    String bookPublisherText =cursor.getString(cursor.getColumnIndex(IProivderMetaData.BookTableMetaData.BOOK_PUBLISHER));    text += "id = " + bookIdText + ",name = " + bookNameText +           ",publisher = " + bookPublisherText + "/n";  }  cursor.close();  mTableInfo.setText(text);}

8.更新数据

String bookId1 = "2";String bookName = "Art";String bookPublisher = "TieDao";ContentValues values2 = new ContentValues();values2.put(IProivderMetaData.BookTableMetaData.BOOK_NAME,bookName);values2.put(IProivderMetaData.BookTableMetaData.BOOK_PUBLISHER,bookPublisher);if ("".equals(bookId1)) {   mContentResolver.update(IProivderMetaData.BookTableMetaData.CONTENT_URI,              values2, null, null);} else {   mContentResolver.update(Uri.withAppendedPath(IProivderMetaData.BookTableMetaData.CONTENT_URI, bookId1),              values2, "_id = ? ", new String[]{bookId1}   );}

三、小案例

1.添加strings.xml文件

  <string name="content_provider">ContentProvider</string>  <string name="add_data">增加数据</string>  <string name="delete_data">删除数据</string>  <string name="update_data">更改数据</string>  <string name="query_data">查询数据</string>

2.修改activity_main.xml文件

<?xml version="1.0" encoding="utf-8"?><android.support.design.widget.CoordinatorLayout 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:fitsSystemWindows="true"  tools:context="com.zhangmiao.datastoragedemo.MainActivity">  <LinearLayout    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical">    <TextView      android:layout_width="wrap_content"      android:layout_height="wrap_content"      android:layout_gravity="center_horizontal"      android:text="@string/content_provider" />    <LinearLayout      android:layout_width="match_parent"      android:layout_height="wrap_content"      android:layout_marginBottom="@dimen/fab_margin"      android:layout_marginTop="@dimen/fab_margin"      android:orientation="horizontal">      <Button        android:id="@+id/provider_add"        android:layout_width="0dp"        android:layout_height="wrap_content"        android:layout_weight="1"        android:text="@string/add_data" />      <Button        android:id="@+id/provider_delete"        android:layout_width="0dp"        android:layout_height="wrap_content"        android:layout_weight="1"        android:text="@string/delete_data" />      <Button        android:id="@+id/provider_update"        android:layout_width="0dp"        android:layout_height="wrap_content"        android:layout_weight="1"        android:text="@string/update_data" />      <Button        android:id="@+id/provider_query"        android:layout_width="0dp"        android:layout_height="wrap_content"        android:layout_weight="1"        android:text="@string/query_data" />    </LinearLayout>    <TextView      android:id="@+id/table_info"      android:layout_width="match_parent"      android:layout_height="wrap_content"      android:text="@string/app_name" />  </LinearLayout></android.support.design.widget.CoordinatorLayout>

3.添加IProviderMetaData接口

package com.zhangmiao.datastoragedemo;import android.net.Uri;import android.provider.BaseColumns;/** * Created by zhangmiao on 2016/12/20. */public interface IProviderMetaData {  public static final String AUTHORITY = "com.zhangmiao.datastoragedemo";  public static final String DB_NAME = "book.db";  public static final int VERSION = 1;  public interface BookTableMetaData extends BaseColumns {    public static final String TABLE_NAME = "book";    public static final Uri CONTENT_URI = Uri.parse("content://"            + AUTHORITY + "/" + TABLE_NAME);    public static final String BOOK_ID = "_id";    public static final String BOOK_NAME = "name";    public static final String BOOK_PUBLISHER = "publisher";    public static final String SORT_ORDER = "_id desc";    public static final String CONTENT_LIST = "vnd.android.cursor.dir/vnd.bookprovider.book";    public static final String CONTENT_ITEM = "vnd.android.cursor.item/vnd.bookprovider.book";  }}

4.添加ContentProviderDBHelper类

package com.zhangmiao.datastoragedemo;import android.content.Context;import android.database.sqlite.SQLiteDatabase;import android.database.sqlite.SQLiteOpenHelper;import android.util.Log;/** * Created by zhangmiao on 2016/12/20. */public class ContentProviderDBHelper extends SQLiteOpenHelper implements IProviderMetaData {  private static final String TAG = "ContentProviderDBHelper";  public ContentProviderDBHelper(Context context) {    super(context, DB_NAME, null, VERSION);  }  @Override  public void onCreate(SQLiteDatabase db) {    String TABLESQL = "CREATE TABLE IF NOT EXISTS "        + BookTableMetaData.TABLE_NAME + " ("        + BookTableMetaData.BOOK_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"        + BookTableMetaData.BOOK_NAME + " VARCHAR,"        + BookTableMetaData.BOOK_PUBLISHER + " VARCHAR)";    db.execSQL(TABLESQL);  }  @Override  public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {    Log.w(TAG, "Upgrading database from version " + oldVersion + "to"        + newVersion + ", which will destroy all old data");    db.execSQL("DROP TABLE IF EXISTS " + DB_NAME);    onCreate(db);  }}

5.添加BookContentProvider类

package com.zhangmiao.datastoragedemo;import android.content.ContentProvider;import android.content.ContentUris;import android.content.ContentValues;import android.content.UriMatcher;import android.database.Cursor;import android.database.sqlite.SQLiteDatabase;import android.net.Uri;import android.support.annotation.Nullable;import android.util.Log;/** * Created by zhangmiao on 2016/12/21. */public class BookContentProvider extends ContentProvider {  private static final String TAG = "BookContentProvider";  private static UriMatcher uriMatcher = null;  private static final int BOOKS = 1;  private static final int BOOK = 2;  private ContentProviderDBHelper dbHelper;  private SQLiteDatabase db;  static {    uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);    uriMatcher.addURI(IProviderMetaData.AUTHORITY,        IProviderMetaData.BookTableMetaData.TABLE_NAME, BOOKS);    uriMatcher.addURI(IProviderMetaData.AUTHORITY,        IProviderMetaData.BookTableMetaData.TABLE_NAME + "/#",        BOOK);  }  @Override  public boolean onCreate() {    dbHelper = new ContentProviderDBHelper(getContext());    return (dbHelper == null) ? false : true;  }  @Nullable  @Override  public String getType(Uri uri) {    switch (uriMatcher.match(uri)) {      case BOOKS:        return IProviderMetaData.BookTableMetaData.CONTENT_LIST;      case BOOK:        return IProviderMetaData.BookTableMetaData.CONTENT_ITEM;      default:        throw new IllegalArgumentException("This is a unKnow Uri"            + uri.toString());    }  }  @Nullable  @Override  public Uri insert(Uri uri, ContentValues values) {    switch (uriMatcher.match(uri)) {      case BOOKS:        db = dbHelper.getWritableDatabase();        long rowId = db.insert(            IProviderMetaData.BookTableMetaData.TABLE_NAME,            IProviderMetaData.BookTableMetaData.BOOK_ID,            values);        Uri insertUri = Uri.withAppendedPath(uri, "/" + rowId);        Log.i(TAG, "insertUri:" + insertUri.toString());        getContext().getContentResolver().notifyChange(uri, null);        return insertUri;      case BOOK:      default:        throw new IllegalArgumentException("This is a unKnow Uri"            + uri.toString());    }  }  @Nullable  @Override  public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {    db = dbHelper.getReadableDatabase();    switch (uriMatcher.match(uri)) {      case BOOKS:        return db.query(IProviderMetaData.BookTableMetaData.TABLE_NAME,            projection, selection, selectionArgs, null, null,            sortOrder);      case BOOK:        long id = ContentUris.parseId(uri);        String where = "_id=" + id;        if (selection != null && !"".equals(selection)) {          where = selection + " and " + where;        }        return db.query(IProviderMetaData.BookTableMetaData.TABLE_NAME,            projection, where, selectionArgs, null, null, sortOrder);      default:        throw new IllegalArgumentException("This is a unKnow Uri"            + uri.toString());    }  }  @Override  public int delete(Uri uri, String selection, String[] selectionArgs) {    db = dbHelper.getWritableDatabase();    switch (uriMatcher.match(uri)) {      case BOOKS:        return db.delete(IProviderMetaData.BookTableMetaData.TABLE_NAME,            selection, selectionArgs);      case BOOK:        long id = ContentUris.parseId(uri);        String where = "_id=" + id;        if (selection != null && !"".equals(selection)) {          where = selection + " and " + where;        }        return db.delete(IProviderMetaData.BookTableMetaData.TABLE_NAME,            selection, selectionArgs);      default:        throw new IllegalArgumentException("This is a unKnow Uri"            + uri.toString());    }  }  @Override  public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {    db = dbHelper.getWritableDatabase();    switch (uriMatcher.match(uri)) {      case BOOKS:        return db.update(IProviderMetaData.BookTableMetaData.TABLE_NAME,            values, null, null);      case BOOK:        long id = ContentUris.parseId(uri);        String where = "_id=" + id;        if (selection != null && !"".equals(selection)) {          where = selection + " and " + where;        }        return db.update(IProviderMetaData.BookTableMetaData.TABLE_NAME,            values, selection, selectionArgs);      default:        throw new IllegalArgumentException("This is a unKnow Uri"            + uri.toString());    }  }}

6.修改AndroidManifest.xml文件

<provider      android:authorities="com.zhangmiao.datastoragedemo"      android:name=".BookContentProvider"/>

7.修改MainActivity

package com.zhangmiao.datastoragedemo;import android.content.ContentResolver;import android.content.ContentValues;import android.database.Cursor;import android.net.*;import android.os.Bundle;import android.support.v7.app.AppCompatActivity;import android.util.Log;import android.view.View;import android.widget.Button;import android.widget.TextView;import java.util.ArrayList;import java.util.List;public class MainActivity extends AppCompatActivity implements View.OnClickListener {private ContentResolver mContentResolver;  private BookContentProvider mBookContentProvider;private TextView mTableInfo;  @Override  protected void onCreate(Bundle savedInstanceState) {    Log.v("MainActivity", "onCreate");    super.onCreate(savedInstanceState);    setContentView(R.layout.activity_main);    Button cpAdd = (Button) findViewById(R.id.provider_add);    Button cpDelete = (Button) findViewById(R.id.provider_delete);    Button cpUpdate = (Button) findViewById(R.id.provider_update);    Button cpQuery = (Button) findViewById(R.id.provider_query);    mTableInfo = (TextView) findViewById(R.id.table_info);    cpAdd.setOnClickListener(this);    cpDelete.setOnClickListener(this);    cpQuery.setOnClickListener(this);    cpUpdate.setOnClickListener(this);  }  @Override  public void onClick(View v) {    switch (v.getId()) {case R.id.provider_add:        mContentResolver = getContentResolver();        String[] bookNames = new String[]{"Chinese", "Math", "English", "Sports"};        String[] bookPublishers = new String[]{"XinHua", "GongXin", "DianZi", "YouDian"};        for (int i = 0; i < bookNames.length; i++) {          ContentValues values = new ContentValues();          values.put(IProviderMetaData.BookTableMetaData.BOOK_NAME, bookNames[i]);          values.put(IProviderMetaData.BookTableMetaData.BOOK_PUBLISHER, bookPublishers[i]);          mContentResolver.insert(IProviderMetaData.BookTableMetaData.CONTENT_URI, values);        }        break;      case R.id.provider_delete:        String bookId = "1";        if (!"".equals(bookId)) {          ContentValues values1 = new ContentValues();          values1.put(IProviderMetaData.BookTableMetaData.BOOK_ID,              bookId);          mContentResolver.delete(              Uri.withAppendedPath(                  IProviderMetaData.BookTableMetaData.CONTENT_URI,                  bookId              ), "_id = ?",              new String[]{bookId}          );        } else {          mContentResolver.delete(              IProviderMetaData.BookTableMetaData.CONTENT_URI,              null,              null          );        }        break;      case R.id.provider_query:        Cursor cursor = mContentResolver.query(IProviderMetaData.BookTableMetaData.CONTENT_URI, null, null, null, null);        String text = "";        if (cursor != null) {          while (cursor.moveToNext()) {            String bookIdText =                cursor.getString(cursor.getColumnIndex(IProviderMetaData.BookTableMetaData.BOOK_ID));            String bookNameText =                cursor.getString(cursor.getColumnIndex(IProviderMetaData.BookTableMetaData.BOOK_NAME));            String bookPublisherText =                cursor.getString(cursor.getColumnIndex(IProviderMetaData.BookTableMetaData.BOOK_PUBLISHER));            text += "id = " + bookIdText + ",name = " + bookNameText + ",publisher = " + bookPublisherText + "/n";          }          cursor.close();          mTableInfo.setText(text);        }        break;      case R.id.provider_update:        String bookId1 = "2";        String bookName = "Art";        String bookPublisher = "TieDao";        ContentValues values2 = new ContentValues();        values2.put(IProviderMetaData.BookTableMetaData.BOOK_NAME,            bookName);        values2.put(IProviderMetaData.BookTableMetaData.BOOK_PUBLISHER,            bookPublisher);        if ("".equals(bookId1)) {          mContentResolver.update(              IProviderMetaData.BookTableMetaData.CONTENT_URI,              values2, null, null);        } else {          mContentResolver.update(              Uri.withAppendedPath(                  IProviderMetaData.BookTableMetaData.CONTENT_URI, bookId1),              values2, "_id = ? ", new String[]{bookId1});        }        break;default:        Log.v("MainActivity", "default");        break;    }  }}

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表