数据持久化有文件存储、SharedPreferences、数据库存储、ContentProvider、网络存储几种方式。
1.文件存储(不包括缓存目录下存储)、网络存储跟平时使用一样
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应为“测试”,如果去掉RePlugin.getHostContext(),弹出的就会是“默认”了。
缓存目录下存储与sp文件类似,插件中需要通过RePlugin.getHostContext()获取目录。
3.数据库存储
宿主项目中新建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(person.name!!, person.description!!))
db.close()
Log.e("dbDao", person.name + ":" + person.description)
}
}
新建数据库存储对象类,Person.kt
class Person {
var name: String? = null
var description: String? = null
}
插件项目中插入数据
//获取宿主类加载器
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)
//调用set方法,传参
nameMethod.invoke(personInstance,"数据哈哈")
descriptionMethod.invoke(personInstance,"试试数据库呵呵")
//获取PersonDao类
val personDao = hostClassLoader.loadClass("com.test.qby.myapplication.dao.PersonDao")
//获取有参构造
val constructor = personDao.getConstructor(Context::class.java)
//获取PersonDao对象
val daoInstance = constructor.newInstance(RePlugin.getHostContext())
//获取插入方法
val insertMethod = personDao.getDeclaredMethod("insert", person)
//调用插入方法
insertMethod.invoke(daoInstance,personInstance)
通过反射来完成数据库操作。
4.ContentProvider使用
宿主项目中DatabaseOpenHelper.kt同上,然后创建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
}
/**
* 初始化时清除旧数据,插入一条数据
*/
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?, selection: String?,
selectionArgs: Array?, sortOrder: String?): Cursor? {
val tableName = getTableName(uri)
showLog(tableName + " 查询数据")
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 + " 插入数据")
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?): Int {
val tableName = getTableName(uri)
showLog(tableName + " 删除数据")
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?): Int {
val tableName = getTableName(uri)
showLog(tableName + " 更新数据")
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 的参数是 Uri,根据 Uri 获取对应的表名
*
* @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
}
/**
* 根据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" //授权
val PERSON_CONTENT_URI = Uri.parse("content://$AUTHORITY/person")
private val TABLE_CODE_PERSON_SINGLE = 1
private val TABLE_CODE_PERSON = 2
init {
//关联不同的 URI 和 code,便于后续 getType
mUriMatcher.addURI(AUTHORITY, "person", TABLE_CODE_PERSON)
//匹配:content://com.test.qby.myapplication.provider.PersonProvider/person/数字,返回值为1
mUriMatcher.addURI(AUTHORITY, "person/#", TABLE_CODE_PERSON_SINGLE)
}
}
}
在清单文件中注册
<provider
android:name=".provider.PersonProvider"
android:authorities="com.test.qby.myapplication.provider.PersonProvider"/>
插件中操作Provider
//ContentProvider
//内容提供者URI
val uri = Uri.parse("content://com.test.qby.myapplication.provider.PersonProvider/person")
//数据
val values = ContentValues()
values.put("name", "yyy")
values.put("description", "你猜我猜不猜你是谁")
//插入操作
val insert = PluginProviderClient.insert(RePlugin.getHostContext(),uri, values)
Log.e(TAG, insert.toString())
//查询操作,获得游标
val cursor = PluginProviderClient.query(RePlugin.getHostContext(),uri, arrayOf("name","description"), null, null, "DESC")
Log.e(TAG, "查询条目数".plus(cursor.count))
//根据查询结果,循环打印结果
if(cursor.moveToNext()){
val name = cursor.getString(cursor.getColumnIndex("name"))
val description = cursor.getString(cursor.getColumnIndex("description"))
Log.e(TAG, "name = $name,description = $description")
}
//关闭游标
cursor.close()
用到反射的地方写起来代码比较多,真正用的时候还是要抽取放到工具类里,优化一下代码。
以上仅个人学习记录,如有疏漏或谬误,欢迎留言交流!