數(shù)據(jù)持久化有文件存儲力麸、SharedPreferences可款、數(shù)據(jù)庫存儲、ContentProvider克蚂、網(wǎng)絡(luò)存儲幾種方式闺鲸。
1.文件存儲(不包括緩存目錄下存儲)、網(wǎng)絡(luò)存儲跟平時使用一樣
2.SharedPreferences使用
在“宿主”中存放
val sharedPreferences = applicationContext.getSharedPreferences("testReplugin", Context.MODE_PRIVATE)
sharedPreferences.edit().putString("first","測試").apply()
在“插件”中取出
val sharedPreferences = RePlugin.getHostContext().applicationContext.getSharedPreferences("testReplugin", Context.MODE_PRIVATE)
val s = sharedPreferences.getString("first", "默認")
//彈出提示
Toast.makeText(this, s.toString(), Toast.LENGTH_SHORT).show()
取出的地方彈出的Toast應(yīng)為“測試”埃叭,如果去掉RePlugin.getHostContext()摸恍,彈出的就會是“默認”了。
緩存目錄下存儲與sp文件類似游盲,插件中需要通過RePlugin.getHostContext()獲取目錄误墓。
3.數(shù)據(jù)庫存儲
宿主項目中新建DatabaseOpenHelper.kt
class DatabaseOpenHelper(context: Context) : SQLiteOpenHelper(context, DB_NAME, null, DB_VERSION) {
companion object {
private val DB_NAME = "person_list.db"
val TABLE_NAME = "person"
private val DB_VERSION = 1
}
override fun onCreate(db: SQLiteDatabase) {
val SQL_CREATE_TABLE = "create table if not exists $TABLE_NAME(_id integer primary key, name varchar(64), description TEXT)"
db.execSQL(SQL_CREATE_TABLE)
}
override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
}
}
用PersonDao.kt作測試
class PersonDao(private val context: Context) {
private var helper: SQLiteOpenHelper? = null
fun insert(person: Person) {
helper = DatabaseOpenHelper(context)
val db = helper!!.writableDatabase
db.execSQL("insert into person(name, description) values(?,?)", arrayOf<Any>(person.name!!, person.description!!))
db.close()
Log.e("dbDao", person.name + ":" + person.description)
}
}
新建數(shù)據(jù)庫存儲對象類,Person.kt
class Person {
var name: String? = null
var description: String? = null
}
插件項目中插入數(shù)據(jù)
//獲取宿主類加載器
val hostClassLoader = RePlugin.getHostClassLoader()
//獲取Person類
val person = hostClassLoader.loadClass("com.test.qby.myapplication.pojo.Person")
//獲取Person對象
val personInstance = person.newInstance()
//獲取set方法
val nameMethod = person.getDeclaredMethod("setName", String::class.java)
val descriptionMethod = person.getDeclaredMethod("setDescription", String::class.java)
//調(diào)用set方法,傳參
nameMethod.invoke(personInstance,"數(shù)據(jù)哈哈")
descriptionMethod.invoke(personInstance,"試試數(shù)據(jù)庫呵呵")
//獲取PersonDao類
val personDao = hostClassLoader.loadClass("com.test.qby.myapplication.dao.PersonDao")
//獲取有參構(gòu)造
val constructor = personDao.getConstructor(Context::class.java)
//獲取PersonDao對象
val daoInstance = constructor.newInstance(RePlugin.getHostContext())
//獲取插入方法
val insertMethod = personDao.getDeclaredMethod("insert", person)
//調(diào)用插入方法
insertMethod.invoke(daoInstance,personInstance)
通過反射來完成數(shù)據(jù)庫操作益缎。
4.ContentProvider使用
宿主項目中DatabaseOpenHelper.kt同上,然后創(chuàng)建PersonProvider.kt繼承ContentProvider
class PersonProvider : ContentProvider() {
private val TAG = this.javaClass.simpleName
private var mDatabase: SQLiteDatabase? = null
private var mContext: Context? = null
private var mTable: String? = null
override fun onCreate(): Boolean {
initProvider()
return false
}
/**
* 初始化時清除舊數(shù)據(jù)然想,插入一條數(shù)據(jù)
*/
private fun initProvider() {
mTable = DatabaseOpenHelper.TABLE_NAME
mContext = context
mDatabase = DatabaseOpenHelper(mContext!!).writableDatabase
Thread(Runnable { mDatabase!!.execSQL("delete from " + mTable!!) }).start()
}
override fun query(uri: Uri, projection: Array<String>?, selection: String?,
selectionArgs: Array<String>?, sortOrder: String?): Cursor? {
val tableName = getTableName(uri)
showLog(tableName + " 查詢數(shù)據(jù)")
when (mUriMatcher.match(uri)) {
TABLE_CODE_PERSON //查詢所有記錄
-> return mDatabase!!.query(tableName, projection, selection, selectionArgs, null, null, null)
TABLE_CODE_PERSON_SINGLE//查詢特定記錄
-> {
val where = expendSelection(uri, selection)
return mDatabase!!.query(tableName, projection, where, selectionArgs, null, null, null)
}
else -> throw IllegalArgumentException("wrong uri")
}
}
override fun insert(uri: Uri, values: ContentValues?): Uri? {
val tableName = getTableName(uri)
showLog(tableName + " 插入數(shù)據(jù)")
val insert = mDatabase!!.insert(tableName, null, values)
mContext!!.contentResolver.notifyChange(uri, null)
return Uri.parse(PERSON_CONTENT_URI.toString() + "/" + insert)
}
override fun delete(uri: Uri, selection: String?, selectionArgs: Array<String>?): Int {
val tableName = getTableName(uri)
showLog(tableName + " 刪除數(shù)據(jù)")
when (mUriMatcher.match(uri)) {
TABLE_CODE_PERSON -> {
val deleteCount = mDatabase!!.delete(tableName, selection, selectionArgs)
if (deleteCount > 0) {
mContext!!.contentResolver.notifyChange(uri, null)
}
return deleteCount
}
TABLE_CODE_PERSON_SINGLE //刪除特定id記錄
-> {
val where = expendSelection(uri, selection)
val deleteCount2 = mDatabase!!.delete(tableName, where, selectionArgs)
if (deleteCount2 > 0) {
mContext!!.contentResolver.notifyChange(uri, null)
}
return deleteCount2
}
else -> throw IllegalArgumentException("wrong uri")
}
}
override fun update(uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array<String>?): Int {
val tableName = getTableName(uri)
showLog(tableName + " 更新數(shù)據(jù)")
when (mUriMatcher.match(uri)) {
TABLE_CODE_PERSON -> return mDatabase!!.update(tableName, values, selection, selectionArgs)
TABLE_CODE_PERSON_SINGLE //更新特定id記錄
-> {
val where = expendSelection(uri, selection)
val updateCount = mDatabase!!.update(tableName, values, where, selectionArgs)
if (updateCount > 0) {
mContext!!.contentResolver.notifyChange(uri, null)
}
return updateCount
}
else -> throw IllegalArgumentException("wrong uri")
}
}
/**
* CRUD 的參數(shù)是 Uri莺奔,根據(jù) Uri 獲取對應(yīng)的表名
*
* @param uri URI
* @return 表名
*/
private fun getTableName(uri: Uri): String {
var tableName = ""
val match = mUriMatcher.match(uri)
when (match) {
TABLE_CODE_PERSON_SINGLE, TABLE_CODE_PERSON -> tableName = DatabaseOpenHelper.TABLE_NAME
}
showLog("UriMatcher " + uri.toString() + ", result: " + match)
return tableName
}
override fun getType(uri: Uri): String? {
when (mUriMatcher.match(uri)) {
TABLE_CODE_PERSON_SINGLE -> return "vnd.android.cursor.item/person"
TABLE_CODE_PERSON -> return "vnd.android.cursor.dir/person"
}
return null
}
/**
* 根據(jù)URI和查詢條件獲取查詢子句
*
* @param uri URI
* @param selection 查詢條件
* @return 查詢子句
*/
private fun expendSelection(uri: Uri, selection: String?): String {
val split = uri.toString().split("/".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
val id = java.lang.Long.getLong(split[split.size - 1])!!
var where = "id=" + id
if (!TextUtils.isEmpty(selection)) {
where += " and " + selection!!
}
return where
}
private fun showLog(s: String) {
Log.d(TAG, s + " : " + Thread.currentThread().name)
}
companion object {
private val mUriMatcher = UriMatcher(UriMatcher.NO_MATCH)
val AUTHORITY = "com.test.qby.myapplication.provider.PersonProvider" //授權(quán)
val PERSON_CONTENT_URI = Uri.parse("content://$AUTHORITY/person")
private val TABLE_CODE_PERSON_SINGLE = 1
private val TABLE_CODE_PERSON = 2
init {
//關(guān)聯(lián)不同的 URI 和 code,便于后續(xù) getType
mUriMatcher.addURI(AUTHORITY, "person", TABLE_CODE_PERSON)
//匹配:content://com.test.qby.myapplication.provider.PersonProvider/person/數(shù)字,返回值為1
mUriMatcher.addURI(AUTHORITY, "person/#", TABLE_CODE_PERSON_SINGLE)
}
}
}
在清單文件中注冊
<provider
android:name=".provider.PersonProvider"
android:authorities="com.test.qby.myapplication.provider.PersonProvider"/>
插件中操作Provider
//ContentProvider
//內(nèi)容提供者URI
val uri = Uri.parse("content://com.test.qby.myapplication.provider.PersonProvider/person")
//數(shù)據(jù)
val values = ContentValues()
values.put("name", "yyy")
values.put("description", "你猜我猜不猜你是誰")
//插入操作
val insert = PluginProviderClient.insert(RePlugin.getHostContext(),uri, values)
Log.e(TAG, insert.toString())
//查詢操作变泄,獲得游標(biāo)
val cursor = PluginProviderClient.query(RePlugin.getHostContext(),uri, arrayOf("name","description"), null, null, "DESC")
Log.e(TAG, "查詢條目數(shù)".plus(cursor.count))
//根據(jù)查詢結(jié)果令哟,循環(huán)打印結(jié)果
if(cursor.moveToNext()){
val name = cursor.getString(cursor.getColumnIndex("name"))
val description = cursor.getString(cursor.getColumnIndex("description"))
Log.e(TAG, "name = $name,description = $description")
}
//關(guān)閉游標(biāo)
cursor.close()
用到反射的地方寫起來代碼比較多妨蛹,真正用的時候還是要抽取放到工具類里屏富,優(yōu)化一下代碼蛙卤。
以上僅個人學(xué)習(xí)記錄狠半,如有疏漏或謬誤,歡迎留言交流神年!