博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
创建自己的内容提供器
阅读量:5053 次
发布时间:2019-06-12

本文共 9022 字,大约阅读时间需要 30 分钟。

创建自己的内容提供器

DatabaseTest

422101-20171021105628802-1173315082.png

新建内容提供器

422101-20171021105802427-1076601023.png

它会自动在AndroidMainfest.xml中生成定义

422101-20171021110015131-1479846719.png

接下来实现继承的方法

package demo.jq.com.databasetest;import android.content.ContentProvider;import android.content.ContentValues;import android.content.UriMatcher;import android.database.Cursor;import android.database.sqlite.SQLiteDatabase;import android.net.Uri;/** * @author jim */public class DatabaseProvider extends ContentProvider {    public static final int BOOK_DIR = 0;    public static final int BOOK_ITEM = 1;    public static final int CATEGORY_DIR = 2;    public static final int CATEGORY_ITEM = 3;    public static final String AUTHORITY = "demo.jq.com.databasetest.provider";    private  static UriMatcher uriMatcher;    private MyDatabaseHelper dbHelper;    static {        uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);        uriMatcher.addURI(AUTHORITY,"book",BOOK_DIR);        uriMatcher.addURI(AUTHORITY,"book/#",BOOK_ITEM);        uriMatcher.addURI(AUTHORITY,"category",CATEGORY_DIR);        uriMatcher.addURI(AUTHORITY,"category/#",CATEGORY_ITEM);    }    @Override    public int delete(Uri uri, String selection, String[] selectionArgs) {        // 删除数据        SQLiteDatabase db = dbHelper.getReadableDatabase();        int deletedRows = 0;        switch (uriMatcher.match(uri)) {            case BOOK_DIR:                deletedRows = db.delete("Book",selection,selectionArgs);                break;            case BOOK_ITEM:                String bookId = uri.getPathSegments().get(1);                deletedRows = db.delete("Book","id = ?",new String[] {bookId});                break;            case CATEGORY_DIR:                deletedRows = db.delete("Category",selection,selectionArgs);                break;            case CATEGORY_ITEM:                String categoryId = uri.getPathSegments().get(1);                deletedRows = db.delete("Category","id = ?",new String[] {categoryId});                break;            default:                break;        }        return deletedRows;    }    @Override    public String getType(Uri uri) {        switch (uriMatcher.match(uri)) {            case BOOK_DIR:                return "book.dir";            case BOOK_ITEM:                return "book.item";            case CATEGORY_DIR:                return "category.dir";            case CATEGORY_ITEM:                return "category.item";        }        return null;    }    @Override    public Uri insert(Uri uri, ContentValues values) {        // 添加数据        SQLiteDatabase db = dbHelper.getWritableDatabase();        Uri uriReturn = null;        switch (uriMatcher.match(uri)) {            case BOOK_DIR:            case BOOK_ITEM:                long newBookId = db.insert("Book",null,values);                uriReturn = Uri.parse("content://"+AUTHORITY+"/book/"+newBookId);                break;            case CATEGORY_DIR:            case CATEGORY_ITEM:                long newCategoryId = db.insert("Category",null,values);                uriReturn = Uri.parse("content://"+AUTHORITY+"/category/"+newCategoryId);                break;            default:                break;        }        return uriReturn;    }    @Override    public boolean onCreate() {        dbHelper =  new MyDatabaseHelper(getContext(),"BookStore.db",null,2);        return true;    }    @Override    public Cursor query(Uri uri, String[] projection, String selection,                        String[] selectionArgs, String sortOrder) {        // 查询数据        SQLiteDatabase db = dbHelper.getReadableDatabase();        Cursor cursor = null;        switch (uriMatcher.match(uri)) {            case BOOK_DIR:                cursor = db.query("Book",projection,selection,selectionArgs,null,null,sortOrder);                break;            case BOOK_ITEM:                String bookId = uri.getPathSegments().get(1);                cursor = db.query("Book",projection,"id = ?",new String[]{bookId},null,null,sortOrder);                break;            case CATEGORY_DIR:                cursor = db.query("Category",projection,selection,selectionArgs,null,null,sortOrder);                break;            case CATEGORY_ITEM:                String categoryId = uri.getPathSegments().get(1);                cursor = db.query("Category",projection,"id = ?",new String[]{categoryId},null,null,sortOrder);                break;            default:                break;        }        return cursor;    }    @Override    public int update(Uri uri, ContentValues values, String selection,                      String[] selectionArgs) {        // 修改数据        SQLiteDatabase db = dbHelper.getReadableDatabase();        int updatedRows = 0;        switch (uriMatcher.match(uri)) {            case BOOK_DIR:                updatedRows = db.update("Book",values,selection,selectionArgs);                break;            case BOOK_ITEM:                String bookId = uri.getPathSegments().get(1);                updatedRows = db.update("Book",values,"id = ?",new String[] {bookId});                break;            case CATEGORY_DIR:                updatedRows = db.update("Category",values,selection,selectionArgs);                break;            case CATEGORY_ITEM:                String categoryId = uri.getPathSegments().get(1);                updatedRows = db.update("Category",values,"id = ?",new String[] {categoryId});                break;            default:                break;        }        return updatedRows;    }}

提供好对外的内容之后。

下面创建一个ProviderTest进行测试。

package demo.jq.com.providertest;import android.content.ContentValues;import android.database.Cursor;import android.net.Uri;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.util.Log;import android.view.View;import android.widget.Button;/** * @author jim */public class MainActivity extends AppCompatActivity {    private String newId;    private static final String TAG = "MainActivity";    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        // 初始化添加数据按钮        Button addData = (Button) findViewById(R.id.add_data);        addData.setOnClickListener(new View.OnClickListener(){            @Override            public void onClick(View v) {                // 添加数据                Uri uri = Uri.parse("content://demo.jq.com.databasetest.provider/book");                ContentValues values = new ContentValues();                values.put("name","A Clash of Kings");                values.put("author","George Martin");                values.put("pages",1040);                values.put("price",22.85);                Uri newUri = getContentResolver().insert(uri,values);                newId = newUri.getPathSegments().get(1);            }        });        // 更改数据        Button updateData = (Button) findViewById(R.id.update_data);        updateData.setOnClickListener(new View.OnClickListener(){            @Override            public void onClick(View v) {                Uri uri = Uri.parse("content://demo.jq.com.databasetest.provider/book/"+newId);                ContentValues values = new ContentValues();                values.put("name","A Storm of Swords");                values.put("pages",1246);                values.put("price",24.05);                getContentResolver().update(uri,values,null,null);            }        });        // 删除数据        Button deleteData = (Button) findViewById(R.id.delete_data);        deleteData.setOnClickListener(new View.OnClickListener(){            @Override            public void onClick(View v) {                Uri uri = Uri.parse("content://demo.jq.com.databasetest.provider/book/"+newId);                getContentResolver().delete(uri,null,null);            }        });        // 查询数据        Button queryData = (Button) findViewById(R.id.query_data);        queryData.setOnClickListener(new View.OnClickListener(){            @Override            public void onClick(View v) {                // 查询数据                Uri uri = Uri.parse("content://demo.jq.com.databasetest.provider/book");                Cursor cursor = getContentResolver().query(uri,null,null,null,null);                if (cursor != null) {                    while (cursor.moveToNext()) {                        String name = cursor.getString(cursor.getColumnIndex("name"));                        String author = cursor.getString(cursor.getColumnIndex("author"));                        int pages = cursor.getInt(cursor.getColumnIndex("pages"));                        double price = cursor.getDouble(cursor.getColumnIndex("price"));                        Log.d(TAG,"book name is "+name);                        Log.d(TAG,"book author is "+author);                        Log.d(TAG,"book pages is "+pages);                        Log.d(TAG,"book price is "+price);                    }                }                cursor.close();            }        });    }}

422101-20171021110707115-1971121078.png

测试有效哦,可以通过uri,在另一个程序中操作数据和获取数据。

转载于:https://www.cnblogs.com/jiqing9006/p/7704125.html

你可能感兴趣的文章
第九次团队作业-测试报告与用户使用手册
查看>>
Equal Sides Of An Array
查看>>
CentOS笔记-用户和用户组管理
查看>>
Mongodb 基本命令
查看>>
Qt中QTableView中加入Check列实现
查看>>
“富豪相亲大会”究竟迷失了什么?
查看>>
控制文件的备份与恢复
查看>>
返回代码hdu 2054 A==B?
查看>>
Flink独立集群1
查看>>
iOS 8 地图
查看>>
20165235 第八周课下补做
查看>>
[leetcode] 1. Two Sum
查看>>
iOS 日常工作之常用宏定义大全
查看>>
PHP的SQL注入技术实现以及预防措施
查看>>
MVC Razor
查看>>
软件目录结构规范
查看>>
Windbg调试Sql Server 进程
查看>>
linux调度器系列
查看>>
mysqladmin
查看>>
解决 No Entity Framework provider found for the ADO.NET provider
查看>>