Android入门之使用Kotlin实现ContentProvider实例

在上一次简单介绍了ContentProvider,在这里给出一个示例。

上一篇简介ContentProvider
下面我们的ContentProvider将创建一个表叫user(id integer, name varchar(30))。实现增、删、改、查。

  • AndroidManifest.xml中声明
    首先,我们在AndroidManifest.xml中声明,
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.example.iplayer">

    
    <application
        android:name=".MainApplication"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
<!--                <action android:name="android.intent.action.MAIN"/>-->
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
        <activity android:name=".StartActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
        <activity android:name=".LoginActivity">
            <intent-filter>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
        <meta-data
            android:name="com.baidu.lbsapi.API_KEY"
            android:value="1pDCI2jrDNKeUalRQN7Cm1ahaAOpOCpM" />
        <service android:name="com.baidu.location.f"
            android:enabled="true"
            android:process=":remote"/>
         <!--要声明的在这里,给出了完整的-->
        <provider
            android:authorities="com.example.iplayer.testprovider"
            android:name=".provider.UserContentProvider"
            android:exported="true"
            />
    </application>
</manifest>
  • 创建OpenHelperDB.kt,来创建数据库
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper

/**
 *
 */
public class OpenHelperDB(context:Context?, baseName:String, version:Int) : SQLiteOpenHelper(context, baseName, null, version) {
    //我们的表的创建语句
    val BASE_TABLE:String = "CREATE TABLE user(" +
            "id integer primary key autoincrement not null," +
            "name varchar(30) not null);"

    /**
     * 创建执行函数
     */
    override fun onCreate(db: SQLiteDatabase?) {
        //创建我们的表
        db?.execSQL(BASE_TABLE)
    }

    /**
     * 更新执行函数
     */
    override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) {

    }

}
  • 创建UserContentProvider.kt,来创建我们的增删改查具体操作。
package com.example.iplayer.provider

import android.content.*
import android.database.Cursor
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
import android.database.sqlite.SQLiteQuery
import android.database.sqlite.SQLiteQueryBuilder
import android.net.Uri

public class UserContentProvider : ContentProvider(){
    companion object{
        /**
         * 用来初始化matcher
         */
        class Matcher(){
            fun get_matcher(AUTHORITY:String, NAME:Int, Names:Int) : UriMatcher{
                val matcher:UriMatcher = UriMatcher(UriMatcher.NO_MATCH)
                matcher.addURI(AUTHORITY, "names", Names)
                matcher.addURI(AUTHORITY, "name/#", NAME)
                return matcher
            }
        }
        val NAME:Int  = 2
        val NAMES:Int = 1
        var NAME_TABLE = "user" //表名
        val AUTHORITY:String = "com.example.iplayer.testprovider"//包名
        val _ID:String = "id"
        var helperDB:OpenHelperDB? = null
        val matcher = Matcher().get_matcher(AUTHORITY, NAME, NAMES) // 定义Uri匹配器
    }

    /**
     * 插入操作
     */
    override fun insert(uri: Uri, values: ContentValues?): Uri? {
        val db:SQLiteDatabase? = helperDB?.readableDatabase
        when(matcher.match(uri)){
            NAMES -> {
                val rowId:Long? = db?.insert(NAME_TABLE, null, values)
                if (rowId != null) {
                    if(rowId > 0){
                        val uri1:Uri = ContentUris.withAppendedId(uri, rowId)
                        context?.contentResolver?.notifyChange(uri1, null)
                        return uri
                    }
                }

            }
            else -> throw IllegalArgumentException("Unrecognized Uri !")
        }
        return null
    }

    /**
     * 查询操作
     */
    override fun query(
        uri: Uri,
        projection: Array<out String>?,
        selection: String?,
        selectionArgs: Array<out String>?,
        sortOrder: String?
    ): Cursor? {
        val db:SQLiteDatabase? = helperDB?.readableDatabase
        when(matcher.match(uri)){
            NAMES -> return db?.query(NAME_TABLE, null, null, null, null, null, null)
            NAME -> return db?.query(NAME_TABLE, null, "id = ?", selectionArgs, null ,null, null)
            else -> throw IllegalArgumentException("Unrecognized Uri !")
        }

    }

    /**
     * 判断是否已经创建
     */
    override fun onCreate(): Boolean {
        helperDB = OpenHelperDB(context, "test.db", 1)
        return true
    }

    /**
     * 更新操作
     */
    override fun update(
        uri: Uri,
        values: ContentValues?,
        selection: String?,
        selectionArgs: Array<out String>?
    ): Int {
        val db:SQLiteDatabase? = helperDB?.readableDatabase
        var num:Int? = 0
        when(matcher.match(uri)){
            NAMES -> num = db?.update(NAME_TABLE, values, selection, selectionArgs)
            else -> throw IllegalArgumentException("Unrecognized Uri !")
        }
        context?.contentResolver?.notifyChange(uri, null)
        return num ?: 0
    }

    /**
     * 删除操作
     */
    override fun delete(uri: Uri, selection: String?, selectionArgs: Array<out String>?): Int {
        val db:SQLiteDatabase? = helperDB?.readableDatabase
        var num:Int? = 0
        when(matcher.match(uri)){
            NAMES -> num = db?.delete(NAME_TABLE, null, null)
            NAME -> {
                val id:Long = ContentUris.parseId(uri)
                val whereClause:String = "$_ID=$id"
                num = db?.delete(NAME_TABLE, whereClause, selectionArgs)
            }
            else -> throw IllegalArgumentException("Unrecognized Uri !")
        }
        context?.contentResolver?.notifyChange(uri, null)
        return num ?: 0
    }

    /**
     * 获取类型
     */
    override fun getType(uri: Uri): String? {
        return null
    }

}
  • 最后,创建Activity来进行测试,我将结果输出在了控制台。
package com.example.iplayer

import android.app.Activity
import android.content.ContentResolver
import android.content.ContentValues
import android.database.Cursor
import android.net.Uri
import android.os.Bundle
import android.view.Window
import android.view.WindowManager
import com.example.iplayer.provider.OpenHelperDB

class StartActivity : Activity(){
    companion object{
        private var helperDB:OpenHelperDB? = null
        private var resolver:ContentResolver? = null
        private val NAME:String = "name"
        private val AUTHORITY:String = "com.example.iplayer.testprovider"
        private val ALL_URI:Uri = Uri.parse("content://$AUTHORITY/names")
        private val SINGLE_URI:Uri = Uri.parse("content://$AUTHORITY/name")
        private val _ID:String = "id"
    }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        requestWindowFeature(Window.FEATURE_NO_TITLE)
        window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN)
        setContentView(R.layout.start_activity)
        Thread(){
            resolver = contentResolver
            helperDB = OpenHelperDB(this, "test.db", 1);
//            helperDB?.readableDatabase?.execSQL("insert into user values(null, ?)", arrayOf("旧名"))
//            insert()
//            delete()
            update()
            query()
        }.start()
//        insert()
//        query()
//        val value =
//        object : Handler() {}.postDelayed(object:Runnable{
//            override fun run() {
//                val intent = Intent(this@StartActivity, LoginActivity::class.java)
//                startActivity(intent)
//                this@StartActivity.finish()
//            }
//        }, 2000)
    }

    /**
     * 查询
     */
    private fun query():Unit{
        val cursor:Cursor? = resolver?.query(ALL_URI, null, null, null, null)
        if(cursor == null) println("cursor为空")
        if(cursor != null){
            while(cursor.moveToNext()){
                var index_name:Int = cursor.getColumnIndex(NAME)
                println(cursor.getString(index_name))
            }
        }
    }

    /**
     * 插入数据
     */
    private fun insert(){
        val values:ContentValues = ContentValues()
        values.put(NAME, "旧名")
        if(resolver == null) println("resolver为空")
        resolver?.insert(ALL_URI, values)
    }

    /**
     * 删除操作
     */
    private fun delete(){
        resolver?.delete(ALL_URI, null, null)
    }

    /**
     * 更新操作
     */
    private fun update(){
        val values:ContentValues = ContentValues()
        values.put(NAME, "新")
        var select:String = "$NAME = ?"
        resolver?.update(ALL_URI, values, select, arrayOf("旧名"))
    }
}

大功告成!
附上文件布局截图:
布局

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值