android 内容提供者(ContentProvider)共享SQLite

android 内容提供者(ContentProvider)共享SQLite

ContentProvider为android提供了一种不同应用之间共享数据的可能,次列提供ContentProvider将SQLite的数据库表 class 共享出来。

1、创建类DBProvider继承ContentProvider,并且重写以下方法:

    a、onCreate() //创建
    b、query(Uri uri, String[] projection, String selection,
            String[] selectionArgs, String sortOrder)//查找
    c、getType(Uri uri)//返回请求的数据类型
    d、insert(Uri uri, ContentValues values)//插入数据
    e、delete(Uri uri, String selection, String[] selectionArgs)//删除数据
    f、update(Uri uri, ContentValues values, String selection,
            String[] selectionArgs)//更新数据

2、在清单文件中标签下注册内容提供者:

        <provider
            android:name=".DBProvider"  //name为类DBProvider的名字,前面加 “.”
            android:authorities="com.example.class_contentporvider_test.DBProvider" >
        </provider>//自定义的内容提供者访问uri

3、创建DBHelper类继承SQLiteOpenHelper,并重写如下方法,创建SQLite文件:

    public DBHelper(Context context) {
        super(context, "test.db", null, 1);
        // TODO Auto-generated constructor stub

    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub
        String sql = "create table class(id integer primary key autoincrement,name varchar(64),number varchar(64))";
        db.execSQL(sql);
    }


    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub

    }

关于SQLite的使用详情,请参照我的上一篇博文:http://blog.csdn.net/q296264785/article/details/53155739


ContentProvider的继承类DBProvider:

UriMatcher 工具类为Uri解析提供匹配规则,UriMatcher 的实现类提供addURI方法可以往UriMatcher 添加匹配规则。addURI的第一个参数为清单文件中我们自定义的android:authorities=”com.example.class_contentporvider_test.DBProvider”;
第二个参数为访问数据库文件的目录,“*”“#”为通配符,分别代表“字符”“数字”;第三个为自定义常量。

    private DBHelper helper;
    private final static UriMatcher URI_MATCHER = new UriMatcher(
            UriMatcher.NO_MATCH);
    private final static int one = 1;
    private final static int two = 2;
    static {
        // 添加匹配规则
        URI_MATCHER.addURI("com.example.class_contentporvider_test.DBProvider",
                "class", two);// 字符
        URI_MATCHER.addURI("com.example.class_contentporvider_test.DBProvider",
                "class/#", one);// 数字
    }

文件目录表

这里写图片描述

MainActivity :

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}

DBHelper 类:

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

public class DBHelper extends SQLiteOpenHelper {
    private static final String SLQ_NAME = "mydb.db";
    private static final int VERSION = 1; // ctrl + shift + x 小写变大写

    public DBHelper(Context context) {
        super(context, SLQ_NAME, null, VERSION);
        // TODO Auto-generated constructor stub
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub
        String sql = "create table person(_pid integer primary key autoincrement,name varchar(64),address varchar(64))";
        db.execSQL(sql);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub

    }

}

PersonContentProvider 类

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 PersonContentProvider extends ContentProvider {
    private DBHelper helper;
    private final static UriMatcher URI_MATCHER = new UriMatcher(
            UriMatcher.NO_MATCH);
    private final static int PERSONS = 1;// 操作多条记录
    private final static int PERSON = 2;// 操作单行记录
    static {
        // url ,路径 ,
        URI_MATCHER.addURI(
//    "content://com.example.class_contentprovider.PersonContentProvider/person"  添加
                "com.example.class_contentprovider.PersonContentProvider",
                "person", PERSONS);
        URI_MATCHER.addURI(
                "com.example.class_contentprovider.PersonContentProvider",
                "person/#", PERSON);
//相当于 "com.example.class_contentprovider.PersonContentProvider" + "person/#" + PERSON 的uil
    }

    @Override
    public boolean onCreate() {
        // TODO Auto-generated method stub
        helper = new DBHelper(getContext());
        return false;
    }

    @Override 
    public Cursor query(Uri uri, String[] projection, String selection,
            String[] selectionArgs, String sortOrder) {
        // TODO Auto-generated method stub
        Cursor cursor = null;
        int flag = URI_MATCHER.match(uri);
        SQLiteDatabase database = helper.getReadableDatabase();
        switch (flag) {
        case PERSON:
            long _id = ContentUris.parseId(uri);
            String where_value = "_pid = " + _id;
            if (selection != null && !selection.equals("")) {
                where_value += selection;
            }
            cursor = database.query("person", projection, where_value,
                    selectionArgs, null, null, sortOrder);
            break;
        case PERSONS:
            cursor = database.query("person", projection, selection,
                    selectionArgs, null, null, sortOrder);
            break;

        }
        return cursor;
    }

    @Override
    public String getType(Uri uri) {// 返回处理请求的数据类型
        // TODO Auto-generated method stub
        // 先解析uri,判断mime的类型
        int flag = URI_MATCHER.match(uri);
        switch (flag) {
        case PERSON:

            return "vnd.android.cursor.item/person";
        case PERSONS:

            return "vnd.android.cursor.dir/person";
        }
        return null;
    }

    @Override
    public Uri insert(Uri uri, ContentValues values) {
        // TODO Auto-generated method stub
        Uri result = null;
        int flag = URI_MATCHER.match(uri);
        switch (flag) {
        case PERSONS:
            SQLiteDatabase database = helper.getReadableDatabase();
            long id = database.insert("person", null, values);
            result = ContentUris.withAppendedId(uri, id);
            break;
        }
        return result;
    }

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        // TODO Auto-generated method stub
        int flag = URI_MATCHER.match(uri);
        SQLiteDatabase database = helper.getWritableDatabase();
        int count = 0;
        switch (flag) {
        case PERSON:
            long _id = ContentUris.parseId(uri);
            String where_value = "_pid = " + _id;
            if (selection != null && !selection.equals("")) {
                where_value += selection;
            }
            count = database.delete("person", where_value, selectionArgs);
            break;
        case PERSONS:
            count = database.delete("person", selection, selectionArgs);
            break;
        }
        return count;
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection,
            String[] selectionArgs) {
        // TODO Auto-generated method stub
        int flag = URI_MATCHER.match(uri);
        int count = 0;
        SQLiteDatabase database = helper.getWritableDatabase();
        switch (flag) {
        case PERSON:
            long _id = ContentUris.parseId(uri);
            String where_value = "_pid = " + _id;
            if (selection != null && !selection.equals("")) {
                where_value += selection;
            }
            count = database.update("person", values, where_value,
                    selectionArgs);
            break;
        }
        return count;
    }

}

单元测试类:

import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.test.AndroidTestCase;

public class MyTest extends AndroidTestCase {
    public void add() {// 添加
        ContentResolver contentResolver = getContext().getContentResolver();
        ContentValues values = new ContentValues();
        values.put("name", "源信");
        values.put("address", "高新区");
        Uri uri = Uri
                .parse("content://com.example.class_contentprovider.PersonContentProvider/person");
        contentResolver.insert(uri, values);
    }

    public void del() {// 删除
        ContentResolver contentResolver = getContext().getContentResolver();
        Uri uri = Uri
                .parse("content://com.example.class_contentprovider.PersonContentProvider/person");
        Uri new_uri = ContentUris.withAppendedId(uri, 1);
        contentResolver.delete(new_uri, null, null);
    }

    public void query() {// 查找
        ContentResolver contentResolver = getContext().getContentResolver();
        Uri uri = Uri
                .parse("content://com.example.class_contentprovider.PersonContentProvider/person");
        Uri new_uri = ContentUris.withAppendedId(uri, 2);
        Cursor cursor = contentResolver.query(new_uri, null, null, null, null);
        while (cursor.moveToNext()) {
            String str = cursor.getString(cursor.getColumnIndex("name"));
            System.out.println("---query->>" + str);
        }
    }
}
发布了34 篇原创文章 · 获赞 10 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/q296264785/article/details/53158873