自定义ContentProvider及使用ContentResolver解析详细步骤

来源:互联网 发布:mac菜单栏显示器图标 编辑:程序博客网 时间:2024/05/18 06:21

1、在一个提供私有数据的应用中创建一个数据库,包含两张表,继承 SQLiteOpenHelper

package com.example.privatedatabase;import android.content.Context;import android.database.sqlite.SQLiteDatabase;import android.database.sqlite.SQLiteOpenHelper;public class MyOpenHelper extends SQLiteOpenHelper {    public MyOpenHelper(Context context) {        super(context, "Account.db", null, 1);        // TODO Auto-generated constructor stub    }    @Override    public void onCreate(SQLiteDatabase db) {        // TODO Auto-generated method stub        db.execSQL("create table info(_id integer primary key AUTOINCREMENT,name varchar(20),money varchar(20))");        db.execSQL("insert into info(name,money) values(?,?)", new String[] {            "张三", "5000" });        db.execSQL("insert into info(name,money) values(?,?)", new String[] {            "李四", "3000" });        db.execSQL("create table telephony(_id integer primary key AUTOINCREMENT,name varchar(20),phoneNo varchar(20))");        db.execSQL("insert into telephony(name,phoneNo) values(?,?)", new String[] {            "张三", "13932568098" });        db.execSQL("insert into telephony(name,phoneNo) values(?,?)", new String[] {            "李四", "13230569896" });    }    @Override    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {        // TODO Auto-generated method stub    }}

2、在提供私有数据的应用中创建一个内容提供者,向外暴露CRUD方法

package com.example.privatedatabase;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;public class AccountProvider extends ContentProvider {    private SQLiteDatabase db;    private static final int INFO_QUERY_SUCCESS = 1;    private static final int INFO_INSERT_SUCCESS = 2;    private static final int INFO_DELETE_SUCCESS = 3;    private static final int INFO_UPDATE_SUCCESS = 4;    private static final int TELEPHONY_QUERY_SUCCESS = 5;    private static final int TELEPHONY_INSERT_SUCCESS = 6;    private static final int TELEPHONY_DELETE_SUCCESS = 7;    private static final int TELEPHONY_UPDATE_SUCCESS = 8;    private static final UriMatcher sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);    static {        sUriMatcher.addURI("com.zhjg.provider", "queryInfo", INFO_QUERY_SUCCESS);        sUriMatcher.addURI("com.zhjg.provider", "insertInfo",INFO_INSERT_SUCCESS);        sUriMatcher.addURI("com.zhjg.provider", "deleteInfo",INFO_DELETE_SUCCESS);        sUriMatcher.addURI("com.zhjg.provider", "updateInfo",INFO_UPDATE_SUCCESS);        sUriMatcher.addURI("com.zhjg.provider", "queryTelephony",TELEPHONY_QUERY_SUCCESS);        sUriMatcher.addURI("com.zhjg.provider", "insertTelephony",TELEPHONY_INSERT_SUCCESS);        sUriMatcher.addURI("com.zhjg.provider", "deleteTelephony",TELEPHONY_DELETE_SUCCESS);        sUriMatcher.addURI("com.zhjg.provider", "updateTelephony",TELEPHONY_UPDATE_SUCCESS);    }    @Override    public boolean onCreate() {        MyOpenHelper helper = new MyOpenHelper(getContext());        db = helper.getReadableDatabase();        return false;    }    @Override    public Cursor query(Uri uri, String[] projection, String selection,        String[] selectionArgs, String sortOrder) {        int code = sUriMatcher.match(uri);        if (code == INFO_QUERY_SUCCESS) {            Cursor cursor = db.query("info", projection, selection,                selectionArgs, null, null, sortOrder);            return cursor;        } else if (code == TELEPHONY_QUERY_SUCCESS) {            Cursor cursor = db.query("telephony", projection, selection,                selectionArgs, null, null, sortOrder);            return cursor;        } else {            throw new IllegalArgumentException("路径不匹配或当前数据库中没有数据结果!");        }    }    @Override    public String getType(Uri uri) {        // TODO Auto-generated method stub        return null;    }    @Override    public Uri insert(Uri uri, ContentValues values) {        int code = sUriMatcher.match(uri);        if (code == INFO_INSERT_SUCCESS) {            /**             * return: the row ID of the newly inserted row, or -1 if an error             * occurred             */            long id = db.insert("info", null, values);            return ContentUris.withAppendedId(uri, id);        } else if (code == TELEPHONY_INSERT_SUCCESS) {            long id = db.insert("telephony", null, values);            return ContentUris.withAppendedId(uri, id);        } else {            return null;        }    }    @Override    public int delete(Uri uri, String selection, String[] selectionArgs) {        int code = sUriMatcher.match(uri);        if (code == INFO_DELETE_SUCCESS) {            int count = db.delete("info", selection, selectionArgs);            return count;        } else if (code == TELEPHONY_DELETE_SUCCESS) {            int count = db.delete("telephony", selection, selectionArgs);            return count;        } else {            return 0;        }    }    @Override    public int update(Uri uri, ContentValues values, String selection,        String[] selectionArgs) {        int code = sUriMatcher.match(uri);        if (code == INFO_UPDATE_SUCCESS) {            int count = db.update("info", values, selection, selectionArgs);            return count;        } else if (code == TELEPHONY_UPDATE_SUCCESS) {            int count = db                .update("telephony", values, selection, selectionArgs);            return count;        } else {            return 0;        }    }}

3、在提供私有数据的应用的清单文件中注册此ContentProvider

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.example.privatedatabase"    android:versionCode="1"    android:versionName="1.0" >    <uses-sdk        android:minSdkVersion="8"        android:targetSdkVersion="21" />    <application        android:allowBackup="true"        android:icon="@drawable/ic_launcher"        android:label="@string/app_name"        android:theme="@style/AppTheme" >        <activity            android:name="com.example.privatedatabase.MainActivity"            android:label="@string/app_name" >            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>        <provider            android:name="com.example.privatedatabase.AccountProvider"            android:authorities="com.zhjg.provider" >        </provider>    </application></manifest>

4、在其它应用中使用 ContentResolver 中解析 ContentProvider 中的数据

package com.example.readprivatedatabase;import android.content.ContentResolver;import android.content.ContentValues;import android.database.Cursor;import android.net.Uri;import android.os.Bundle;import android.support.v7.app.ActionBarActivity;import android.view.View;public class MainActivity extends ActionBarActivity {    private ContentResolver resolver;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        resolver = getContentResolver();    }    public void clickInsertM(View v) {        // 这里只能逐条添加记录        ContentValues values = new ContentValues();        values.put("name", "王五");        values.put("money", "10000");        resolver.insert(Uri.parse("content://com.zhjg.provider/insertInfo"),            values);    }    public void clickUpdateM(View v) {        ContentValues values = new ContentValues();        values.put("money", "18800");        resolver.update(Uri.parse("content://com.zhjg.provider/updateInfo"),            values, "name=?", new String[] { "王五" });    }    public void clickDeleteM(View v) {        resolver.delete(Uri.parse("content://com.zhjg.provider/deleteInfo"),            "name=?", new String[] { "王五" });    }    public void clickQueryM(View v) {        Cursor cursor = resolver.query(            Uri.parse("content://com.zhjg.provider/queryInfo"), null, null,            null, null);        while (cursor.moveToNext()) {            System.out.println("使用内容提供者,以按钮点击::"                + cursor.getInt(cursor.getColumnIndex("_id")) + " -- "                + cursor.getString(cursor.getColumnIndex("name")) + " -- "                + cursor.getString(cursor.getColumnIndex("money")));        }    }    public void clickInsertP(View v) {        // 这里只能逐条添加记录        ContentValues values = new ContentValues();        values.put("name", "王五");        values.put("phoneNo", "phoneNo10000");        resolver.insert(Uri.parse("content://com.zhjg.provider/insertTelephony"),            values);    }    public void clickUpdateP(View v) {        ContentValues values = new ContentValues();        values.put("phoneNo", "phoneNo18800");        resolver.update(            Uri.parse("content://com.zhjg.provider/updateTelephony"),            values, "name=?", new String[] { "王五" });    }    public void clickDeleteP(View v) {        resolver.delete(            Uri.parse("content://com.zhjg.provider/deleteTelephony"),            "name=?", new String[] { "王五" });    }    public void clickQueryP(View v) {        Cursor cursor = resolver.query(            Uri.parse("content://com.zhjg.provider/queryTelephony"), null,            null, null, null);        while (cursor.moveToNext()) {            System.out.println("使用内容提供者,以按钮点击::"                + cursor.getInt(cursor.getColumnIndex("_id")) + " -- "                + cursor.getString(cursor.getColumnIndex("name")) + " -- "                + cursor.getString(cursor.getColumnIndex("phoneNo")));        }    }}

布局文件

<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"    android:paddingLeft="@dimen/activity_horizontal_margin"    android:paddingRight="@dimen/activity_horizontal_margin"    android:paddingTop="@dimen/activity_vertical_margin"    tools:context="com.example.readprivatedatabase.MainActivity" >    <Button        android:id="@+id/button1"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_below="@+id/textView1"        android:onClick="clickInsertM"        android:text="增加M" />    <Button        android:id="@+id/button2"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignLeft="@+id/button1"        android:layout_below="@+id/button1"        android:onClick="clickUpdateM"        android:text="修改M" />    <Button        android:id="@+id/button3"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignLeft="@+id/button2"        android:layout_below="@+id/button2"        android:onClick="clickDeleteM"        android:text="删除M" />    <Button        android:id="@+id/button4"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignLeft="@+id/button3"        android:layout_below="@+id/button3"        android:onClick="clickQueryM"        android:text="查询全部M" />    <Button        android:id="@+id/button5"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignBaseline="@+id/button1"        android:layout_alignBottom="@+id/button1"        android:layout_marginLeft="42dp"        android:layout_toRightOf="@+id/button4"        android:onClick="clickInsertP"        android:text="增加P" />    <Button        android:id="@+id/button6"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignBaseline="@+id/button2"        android:layout_alignBottom="@+id/button2"        android:layout_alignLeft="@+id/button5"        android:onClick="clickUpdateP"        android:text="修改P" />    <Button        android:id="@+id/button7"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_above="@+id/button4"        android:layout_alignLeft="@+id/button6"         android:onClick="clickDeleteP"        android:text="删除P"  />    <Button        android:id="@+id/button8"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignLeft="@+id/button7"        android:layout_below="@+id/button7"         android:onClick="clickQueryP"        android:text="查询全部P" /></RelativeLayout>

5、图片效果
分别更改info和telephony

这里写图片描述

0 0
原创粉丝点击