Android 組件之ContentProvider

ContentProvider

ContentProvider 是Android中提供的專門用於不同應用間進行數據共享的方式。

下面創建BookContentProvider繼承ContentProvider並實現它的6個方法。

package com.example.test.provider;

import android.content.ContentProvider;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;

/**
 * Description:
 */

public class BookContentProvider extends ContentProvider {
    private static final String TAG = "BookContentProvider";
    @Override
    public boolean onCreate() {
        Log.d(TAG, "onCreate: threadName ---"+Thread.currentThread().getName());
        return false;
    }

    @Nullable
    @Override
    public Cursor query(@NonNull Uri uri, @Nullable String[] projection, @Nullable String selection, @Nullable String[] selectionArgs, @Nullable String sortOrder) {
        Log.d(TAG, "query: threadName ---"+Thread.currentThread().getName());
        return null;
    }

    @Nullable
    @Override
    public String getType(@NonNull Uri uri) {
        Log.d(TAG, "getType: ");
        return null;
    }

    @Nullable
    @Override
    public Uri insert(@NonNull Uri uri, @Nullable ContentValues values) {
        Log.d(TAG, "insert: ");
        return null;
    }

    @Override
    public int delete(@NonNull Uri uri, @Nullable String selection, @Nullable String[] selectionArgs) {
        Log.d(TAG, "delete: ");
        return 0;
    }

    @Override
    public int update(@NonNull Uri uri, @Nullable ContentValues values, @Nullable String selection, @Nullable String[] selectionArgs) {
        Log.d(TAG, "update: ");
        return 0;
    }
}

在AndroidManifest.xml中註冊

 		<provider
            android:authorities="com.example.test.provider.BookContentProvider"
            android:name=".provider.BookContentProvider"
            android:process=":BookContentProvider"
            android:permission="Permission.BookContentProvider"
            >

        </provider>

 	<uses-permission android:name="Permission.BookContentProvider"/>
    <permission android:name="Permission.BookContentProvider"
                android:protectionLevel="normal" />

使用SQLiteOpenHelper創建數據庫,並通過BookContentProvider 對外提供訪問數據庫中的數據。

package com.example.test.provider;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

/**
 * Description:
 */

public class DBSqlitOpenHelper extends SQLiteOpenHelper{

    private static String DBName = "book.db";
    private static String bookTableName = "book";
    private static String userTableName = "user";
    private static int mVersion = 1;



    private static DBSqlitOpenHelper instance = null;
    private DBSqlitOpenHelper(Context context) {
        super(context, DBName, null,mVersion);
    }
    public static DBSqlitOpenHelper getInstance(Context context) {
        if (instance == null) {
            synchronized (DBSqlitOpenHelper.class) {
                if (instance == null)
                    instance = new DBSqlitOpenHelper(context);
            }
        } return instance;
    }


    @Override
    public void onCreate(SQLiteDatabase db) {
        String bookSql = "create table if not exists "+bookTableName+" (_id integer primary key autoincrement, name nchar,price nchar)";
        String userSql = "create table if not exists "+userTableName+" (_id integer primary key autoincrement, name nchar,age nchar)";
        db.execSQL(bookSql);
        db.execSQL(userSql);

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }
}

修改BookContentProvider

package com.example.test.provider;

import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;

/**
 * Description:
 */

public class BookContentProvider extends ContentProvider {
    private static final String TAG = "BookContentProvider";
    private static final String authority = "com.example.test.provider.BookContentProvider";
    private static final Uri BOOKURI = Uri.parse("content://"+authority+"/book");
    private static final Uri USERURI = Uri.parse("content://"+authority+"/user");
    private static final int BOOKCODE = 0;
    private static final int USERCODE = 1;
    private static final UriMatcher mUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
    static {
        mUriMatcher.addURI(authority,"book",BOOKCODE);
        mUriMatcher.addURI(authority,"user",USERCODE);
    }

    private Context mContext;
    private SQLiteDatabase mDB;

    @Override
    public boolean onCreate() {
        mContext = getContext();
        Log.d(TAG, "onCreate: threadName ---"+Thread.currentThread().getName());
        initData();
        return true;
    }

    private void initData() {
        mDB = DBSqlitOpenHelper.getInstance(mContext).getWritableDatabase();
    }

    @Nullable
    @Override
    public Cursor query(@NonNull Uri uri, @Nullable String[] projection, @Nullable String selection, @Nullable String[] selectionArgs, @Nullable String sortOrder) {
        Log.d(TAG, "query: threadName ---"+Thread.currentThread().getName());
        //查詢數據
        String tableName = getTableName(uri);
        if (tableName == null) {
            throw new IllegalArgumentException("錯誤錯誤。Unsupported URI: "+uri);
        }
        return mDB.query(tableName,projection,selection,selectionArgs,null,null,sortOrder,null);
    }

    @Nullable
    @Override
    public String getType(@NonNull Uri uri) {
        Log.d(TAG, "getType: ");
        return null;
    }

    @Nullable
    @Override
    public Uri insert(@NonNull Uri uri, @Nullable ContentValues values) {
        Log.d(TAG, "insert: ");
        //添加數據
        String tableName = getTableName(uri);
        if (tableName == null) {
            throw new IllegalArgumentException("錯誤錯誤。Unsupported URI: "+uri);
        }
        mDB.insert(tableName,null,values);
        mContext.getContentResolver().notifyChange(uri,null);
        return uri;
    }

    @Override
    public int delete(@NonNull Uri uri, @Nullable String selection, @Nullable String[] selectionArgs) {
        Log.d(TAG, "delete: ");
        //刪除數據
        String tableName = getTableName(uri);
        if (tableName == null) {
            throw new IllegalArgumentException("錯誤錯誤。Unsupported URI: "+uri);
        }
        int count = mDB.delete(tableName, selection, selectionArgs);
        if (count > 0) {
            mContext.getContentResolver().notifyChange(uri,null);
        }
        return count;
    }

    @Override
    public int update(@NonNull Uri uri, @Nullable ContentValues values, @Nullable String selection, @Nullable String[] selectionArgs) {
        Log.d(TAG, "update: ");
        //修改數據
        String tableName = getTableName(uri);
        if (tableName == null) {
            throw new IllegalArgumentException("錯誤錯誤。Unsupported URI: "+uri);
        }
        int row = mDB.update(tableName, values,selection, selectionArgs);
        if (row > 0) {
            mContext.getContentResolver().notifyChange(uri,null);
        }
        return row;
    }

    public String getTableName(Uri uri){
        String tableName = null;
        switch (mUriMatcher.match(uri)){
            case BOOKCODE:
                tableName = DBSqlitOpenHelper.bookTableName;
                break;
            case USERCODE:
                tableName = DBSqlitOpenHelper.userTableName;
                break;
                default:
                    break;
        }
        return tableName;
    }
}

接下來創建ProviderActivity並對BookContentProvider進行訪問,看其是否正常。

package com.example.test.provider;

import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.example.test.R;
import com.example.test.aidl.Book;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ProviderActivity extends AppCompatActivity {

    private static final String TAG = "ProviderActivity";
    @BindView(R.id.tv_add)
    TextView mTvAdd;
    @BindView(R.id.tv_del)
    TextView mTvDel;
    @BindView(R.id.tv_update)
    TextView mTvUpdate;
    @BindView(R.id.tv_query)
    TextView mTvQuery;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_provider);
        ButterKnife.bind(this);


        initData();
    }

    private void initData() {
        Uri bookUri = Uri.parse("content://com.example.test.provider.BookContentProvider" + "/book");

        ContentValues values = new ContentValues();
        values.put("name", "西遊記");
        values.put("price", "199");
        //將西遊記這本書添加到數據庫中
        getContentResolver().insert(bookUri, values);
        Cursor bookCursor = getContentResolver().query(bookUri, new String[]{"_id", "name", "price"}, null, null, null);
        while (bookCursor.moveToNext()) {
            Book book = new Book();
            book.setBookId(bookCursor.getInt(0));
            book.setBookName(bookCursor.getString(1));
            book.setPrice(bookCursor.getString(2));

            Log.e(TAG, "Book: bookName ————" + book.getBookName() + "|||  bookId ————" + book.getBookId() + "  |||  price ————" + book.getPrice());
        }
        bookCursor.close();


        Uri userUri = Uri.parse("content://com.example.test.provider.BookContentProvider" + "/user");
        ContentValues userValues = new ContentValues();
        userValues.put("_id",1);
        userValues.put("name", "孫悟空");
        userValues.put("age", 18);
        //將孫悟空這個用戶添加到數據庫中
        getContentResolver().insert(userUri, userValues);
        Cursor userCursor = getContentResolver().query(userUri, new String[]{"_id", "name", "age"}, null, null, null);
        while (userCursor.moveToNext()) {
            User user = new User();

            user.setUserId(userCursor.getInt(0));
            user.setUserName(userCursor.getString(1));
            user.setAge(userCursor.getInt(2));

            Log.e(TAG, "User: userName ————" + user.getUserName() + "  |||  age ————" + user.getAge() + "|||  userId ————" + user.getUserId());
        }
        userCursor.close();

    }

    @OnClick({R.id.tv_add, R.id.tv_del, R.id.tv_update, R.id.tv_query})
    public void onViewClicked(View view) {
        Uri userUri = Uri.parse("content://com.example.test.provider.BookContentProvider" + "/user");

        switch (view.getId()) {
            case R.id.tv_add:
                ContentValues userValues = new ContentValues();
                userValues.put("_id",2);
                userValues.put("name", "沙和尚");
                userValues.put("age", 20);
                //沙和尚
                getContentResolver().insert(userUri, userValues);

                break;
            case R.id.tv_del:
                //將id爲2的這個用戶刪除
                getContentResolver().delete(userUri,"_id=?", new String[]{String.valueOf(2)});
                break;
            case R.id.tv_update:
                ContentValues values = new ContentValues();
                values.put("age", 30);
                //將id爲2的這個用戶修改年齡爲30
                getContentResolver().update(userUri,values,"_id=?", new String[]{String.valueOf(2)});
                break;
            case R.id.tv_query:
                Cursor userCursor = getContentResolver().query(userUri, new String[]{"_id", "name", "age"}, null, null, null);
                while (userCursor.moveToNext()) {
                    User user = new User();
                    user.setUserId(userCursor.getInt(0));
                    user.setUserName(userCursor.getString(1));
                    user.setAge(userCursor.getInt(2));

                    Log.e(TAG, "User: userName ————" + user.getUserName() + "  |||  age ————" + user.getAge() + "|||  userId ————" + user.getUserId());
                }
                userCursor.close();
                break;
        }
    }
}


運行程序,可以看到數據已經存進去並查詢出來
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章