Android content provider (ContentProvider) sharing SQLite

Android content provider (ContentProvider) sharing SQLite

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

1. Create a class DBProvider that inherits ContentProvider, and rewrite the following methods:

    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. Register the content provider under the label in the manifest file:

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

3. Create DBHelper class to inherit SQLiteOpenHelper, and rewrite the following method to create SQLite file:

    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

    }

For details of using SQLite, please refer to my previous blog post: http://blog.csdn.net/q296264785/article/details/53155739


ContentProvider的继承类DBProvider:

The UriMatcher tool class provides matching rules for Uri parsing. The UriMatcher implementation class provides addURI methods to add matching rules to UriMatcher. The first parameter of addURI is our custom android: authorities = ”com.example.class_contentporvider_test.DBProvider” in the manifest file; the
second parameter is the directory to access the database file, “*” “#” is a wildcard, respectively "Character" "Number"; the third is a custom constant.

    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);// 数字
    }

File directory table

Write a picture description here

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 class:

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 class

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

}

Unit test class:

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);
        }
    }
}
Published 34 original articles · Like 10 · Visits 30,000+

Guess you like

Origin blog.csdn.net/q296264785/article/details/53158873