欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

《第一行代码》学习笔记——第七章 内容提供器

程序员文章站 2022-06-26 14:49:35
《第一行代码》学习笔记——第七章 内容提供器内容提供器简介访问其他程序中的数据读取系统联系人内容提供器简介内容提供器主要用于在不用的应用程序之间实现数据共享的功能。访问其他程序中的数据读取系统联系人Cursor cursor = null;try { cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null...

内容提供器简介

内容提供器主要用于在不用的应用程序之间实现数据共享的功能。

访问其他程序中的数据

读取系统联系人

	Cursor cursor = null;
	try {
	    cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
	            null, null, null, null);
	    if (cursor != null) {
	        while (cursor.moveToNext()) {
	            String displayName = cursor.getString(
	                    cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
	            String number = cursor.getString(
	                    cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
	            contactsList.add(displayName + "\n" + number);
	        }
	        adapter.notifyDataSetChanged();
	    }
	} catch (Exception e) {
	    e.printStackTrace();
	} finally {
	    if (cursor != null)
	        cursor.close();
	}

创建自定义内容提供器

标准Uri写法:

	content://com.example.app.provider/table1/1

表示希望访问com.example.app这个应用的table表中id为1的数据

通配符 描述
* 表示匹配任意长度的任意字符
# 表示匹配任意长度的数字

匹配任意表内容:

	content://com.example.app.provider/*

匹配表table1中任意一行数据:

	content://com.example.app.provider/table1/#

使用UriMatcher类匹配URI

UriMatcher提供addURI()方法添加一个Uri和对应的自定义码:

	uriMatcher.addURI("com.example.app.provider", "table1", 0);

通过调用match()方法,匹配传入的Uri,返回匹配的自定义码:

	int code = uriMatcher.match(uri);

表的MIME类型

描述
类型部分 vnd
子类型部分,单个行 android.cursor.item/
子类型部分,多个行 android.cursor.dir/
提供程序特有部分 vnd.<name>.<type>

表table1的MIME:

	vnd.android.cursor.dir/vnd.com.example.app.provider.table1

表table1中id=1的数据的MIME:

	vnd.android.cursor.item/vnd.com.example.app.provider.table1

创建自定义内容提供器

  1. 新建自定义内容提供器类继承ContentProvider,并实现其方法:
public class DatabaseProvider extends ContentProvider {

    private static final int BOOK_DIR = 0;
    private static final int BOOK_ITEM = 1;
    private static final int CATEGORY_DIR = 2;
    private static final int CATEGORY_ITEM = 3;

    private static final String AUTHORITY = "com.lhh.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.getWritableDatabase();
        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) {
        String type = null;
        switch (uriMatcher.match(uri)) {
            case BOOK_DIR:
                type = "vnd.android.cursor.dir/vnd.com.lhh.databasetest.provider.book";
                break;
            case BOOK_ITEM:
                type = "vnd.android.cursor.item/vnd.com.lhh.databasetest.provider.book";
                break;
            case CATEGORY_DIR:
                type = "vnd.android.cursor.dir/vnd.com.lhh.databasetest.provider.category";
                break;
            case CATEGORY_ITEM:
                type = "vnd.android.cursor.item/vnd.com.lhh.databasetest.provider.category";
                break;
            default:
                break;
        }
        return type;
    }

    @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 bookId = db.insert("Book", null, values);
                uriReturn = Uri.parse("content://" + AUTHORITY + "/book/" + bookId);
                break;
            case CATEGORY_DIR:
            case CATEGORY_ITEM:
                long categoryId = db.insert("Category", null, values);
                uriReturn = Uri.parse("content://" + AUTHORITY + "/category/" + categoryId);
                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.getWritableDatabase();
        int updateRows = 0;
        switch (uriMatcher.match(uri)) {
            case BOOK_DIR:
                updateRows = db.update("Book", values, selection, selectionArgs);
                break;
            case BOOK_ITEM:
                String bookId = uri.getPathSegments().get(1);
                updateRows = db.update("Book", values, "id=?", new String[]{bookId});
                break;
            case CATEGORY_DIR:
                updateRows = db.update("Category", values, selection, selectionArgs);
                break;
            case CATEGORY_ITEM:
                String categoryId = uri.getPathSegments().get(1);
                updateRows = db.update("Category", values, "id=?", new String[]{categoryId});
                break;
            default:
                break;
        }
        return updateRows;
    }
}
  1. 在AndroidManifest.xml中注册内容提供器:
	<provider
	    android:name=".DatabaseProvider"
	    android:authorities="com.lhh.databasetest.provider"
	    android:enabled="true"
	    android:exported="true"/>

android:name属性表示提供程序类名
android:authorities属性表示内容提供器的标识
android:enable属性表示是否启用
android:exported属性表示是否允许其他程序访问

  1. 在其他程序中访问内容提供器
switch (v.getId()) {
	case R.id.add_data:
	    Uri uri = Uri.parse("content://com.lhh.databasetest.provider/book");
	    ContentValues values = new ContentValues();
	    values.put("name", "A * 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);
	    break;
	case R.id.query_data:
	    Uri uri1 = Uri.parse("content://com.lhh.databasetest.provider/book");
	    Cursor cursor = getContentResolver().query(uri1, null, 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.i(TAG, "onClick: name: " + name);
	            Log.i(TAG, "onClick: author: " + author);
	            Log.i(TAG, "onClick: pages: " + pages);
	            Log.i(TAG, "onClick: price: " + price);
	        }
	        cursor.close();
	    }
	    break;
	case R.id.update_data:
	    Uri uri2 = Uri.parse("content://com.lhh.databasetest.provider/book/" + newId);
	    ContentValues values2 = new ContentValues();
	    values2.put("name", "A Storm of Swords");
	    values2.put("pages", 1216);
	    values2.put("price", 24.05);
	    getContentResolver().update(uri2, values2, null, null);
	    break;
	case R.id.delete_data:
	    Uri uri3 = Uri.parse("content://com.lhh.databasetest.provider/book/" + newId);
	    getContentResolver().delete(uri3, null, null);
	    break;
	default:
	    break;
	}

本文地址:https://blog.csdn.net/qq_28673129/article/details/110502546