Android ContentProvider 实现数据库共享

通过继承 ContentProvider 类并重写其方法,可以实现对数据库的增删改查操作,从而实现共享数据库的功能。本文提供一个示例代码,演示如何使用 ContentProvider 来共享数据库。

class DatabaseProvider : ContentProvider() {
    private val bookDir = 0
    private val bookItem = 1
    private val categoryDir = 2
    private val categoryItem = 3
    private val authority = 'com.example.databasetest1.provider'
    private var dbHelper: MyDatabaseHelper? = null

    private val uriMatcher by lazy {
        val matcher = UriMatcher(UriMatcher.NO_MATCH)
        matcher.addURI(authority, 'book', bookDir)
        matcher.addURI(authority, 'book/#', bookItem)
        matcher.addURI(authority, 'category', categoryDir)
        matcher.addURI(authority, 'category/#', categoryItem)
        matcher
    }

    override fun onCreate() = context?.let {
        dbHelper = MyDatabaseHelper(it, 'BookStore.db', 2)
        true
    } ?: false
    override fun query(uri: Uri, projection: Array<String>?, selection: String?, selectionArgs: Array<String>?, sortOrder: String?) = dbHelper?.let {
        // 查询数据
        val db = it.readableDatabase
        val cursor = when (uriMatcher.match(uri)) {
            bookDir -> db.query('Book', projection, selection, selectionArgs, null, null, sortOrder)
            bookItem -> {
                val bookId = uri.pathSegments[1]
                db.query('Book', projection, 'id = ?', arrayOf(bookId), null, null, sortOrder)
            }
            categoryDir -> db.query('Category', projection, selection, selectionArgs, null, null, sortOrder)
            categoryItem -> {
                val categoryId = uri.pathSegments[1]
                db.query('Category', projection, 'id = ?', arrayOf(categoryId), null, null, sortOrder)
            }
            else -> null
        }
        cursor
    }
    override fun insert(uri: Uri, values: ContentValues?) = dbHelper?.let {
        // 添加数据
        val db = it.writableDatabase
        val uriReturn = when (uriMatcher.match(uri)) {
            bookDir, bookItem -> {
                val newBookId = db.insert('Book', null, values)
                Uri.parse('content://$authority/book/$newBookId')
            }
            categoryDir, categoryItem -> {
                val newCategoryId = db.insert('Category', null, values)
                Uri.parse('content://$authority/category/$newCategoryId')
            }
            else -> null
        }
        uriReturn
    }
    override fun update(uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array<String>?) = dbHelper?.let {
        // 更新数据
        val db = it.writableDatabase
        val updatedRows = when (uriMatcher.match(uri)) {
            bookDir -> db.update('Book', values, selection, selectionArgs)
            bookItem -> {
                val bookId = uri.pathSegments[1]
                db.update('Book', values, 'id = ?', arrayOf(bookId))
            }
            categoryDir -> db.update('Category', values, selection, selectionArgs)
            categoryItem -> {
                val categoryId = uri.pathSegments[1]
                db.update('Category', values, 'id = ?', arrayOf(categoryId))
            }
            else -> 0
        }
        updatedRows
    } ?: 0
    override fun delete(uri: Uri, selection: String?, selectionArgs: Array<String>?) = dbHelper?.let {
        // 删除数据
        val db = it.writableDatabase
        val deletedRows = when (uriMatcher.match(uri)) {
            bookDir -> db.delete('Book', selection, selectionArgs)
            bookItem -> {
                val bookId = uri.pathSegments[1]
                db.delete('Book', 'id = ?', arrayOf(bookId))
            }
            categoryDir -> db.delete('Category', selection, selectionArgs)
            categoryItem -> {
                val categoryId = uri.pathSegments[1]
                db.delete('Category', 'id = ?', arrayOf(categoryId))
            }
            else -> 0
        }
        deletedRows
    } ?: 0
    override fun getType(uri: Uri) = when (uriMatcher.match(uri)) {
        bookDir -> 'vnd.android.cursor.dir/vnd.com.example.databasetest1.provider.book'
        bookItem -> 'vnd.android.cursor.item/vnd.com.example.databasetest1.provider.book'
        categoryDir -> 'vnd.android.cursor.dir/vnd.com.example.databasetest1.provider.category'
        categoryItem -> 'vnd.android.cursor.item/vnd.com.example.databasetest1.provider.category'
        else -> null
    }
}

解释:

  1. 继承 ContentProvider 类: 首先,我们需要创建一个类并继承 ContentProvider 类,这是实现数据库共享的必要步骤。
  2. 定义 authorityauthority 是标识 ContentProvider 的唯一字符串,用于在其他应用程序中访问该 ContentProvider。
  3. 创建 UriMatcherUriMatcher 用于匹配 URI,将不同的 URI 映射到不同的操作。
  4. 重写 onCreate 方法: 在 onCreate 方法中,我们初始化数据库,并创建数据库帮助类 MyDatabaseHelper
  5. 重写其他方法: 重写 queryinsertupdatedelete 方法,分别实现数据库的查询、插入、更新、删除操作。
  6. 使用 ContentResolver 访问 ContentProvider: 其他应用程序可以使用 ContentResolver 来访问和操作这个 ContentProvider,从而实现共享数据库的功能。

注意:

  • MyDatabaseHelper 类需要自行实现,用于创建和管理数据库。
  • 在代码中,'Book''Category' 指的是数据库中的表名。
  • 'content://$authority/book/$newBookId''content://$authority/category/$newCategoryId' 是插入数据的返回结果,用于标识新插入数据的 URI。

总结:

使用 ContentProvider 是 Android 平台实现数据库共享的最佳方式,它提供了安全、高效、统一的方式来访问和操作数据库。通过本文提供的示例代码,您可以了解如何使用 ContentProvider 来实现数据库共享,并将其应用到您的 Android 应用开发中。

Android ContentProvider 实现数据库共享

原文地址: https://www.cveoy.top/t/topic/qjCP 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录