Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> Android開發 >> 關於android開發 >> Android之ContentProvider數據存儲,contentprovider

Android之ContentProvider數據存儲,contentprovider

編輯:關於android開發

Android之ContentProvider數據存儲,contentprovider


 一、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;
        }
    }
}

代碼下載地址:https://github.com/ZhangMiao147/DataStorageDemo

參考文章:https://liuzhichao.com/p/562.html

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved