Files
assistant-android/app/src/main/java/com/gh/base/BaseSimpleDao.kt
2021-08-21 10:57:45 +08:00

93 lines
2.6 KiB
Kotlin

package com.gh.base
import android.content.Context
import android.content.SharedPreferences
import com.gh.common.util.SPUtils
import com.halo.assistant.HaloApp
/**
* 用 SP 实现的简单列表持久化结构
*/
abstract class BaseSimpleDao {
// 使用独有的 SP 文件
private val mSp: SharedPreferences by lazy {
HaloApp.getInstance().application.getSharedPreferences("SimpleDao", Context.MODE_PRIVATE)
}
fun add(key: String) {
val originString = SPUtils.getString(mSp, getSPKey())
if (originString.isEmpty()) {
// Insert keyword only for the very first time.
SPUtils.setString(mSp, getSPKey(), key)
} else {
getAll()?.let {
if (getMaxSize() != -1 && it.size > getMaxSize()) {
it.removeAt(it.size - 1)
}
// Move keyword to the very front if it exists.
if (it.contains(key)) {
it.remove(key)
}
it.add(0, key)
val builder = StringBuilder()
for ((index, k) in it.withIndex()) {
builder.append(k)
if (index != it.size - 1) {
builder.append(DIVIDER_KEY)
}
}
SPUtils.setString(mSp, getSPKey(), builder.toString())
}
}
}
fun delete(key: String) {
val originString = SPUtils.getString(mSp, getSPKey())
if (originString.isEmpty()) {
// do nothing
} else {
getAll()?.let {
if (it.contains(key)) {
it.remove(key)
}
val builder = StringBuilder()
for ((index, k) in it.withIndex()) {
builder.append(k)
if (index != it.size - 1) {
builder.append(DIVIDER_KEY)
}
}
SPUtils.setString(mSp, getSPKey(), builder.toString())
}
}
}
fun getAll(): ArrayList<String>? {
val list = SPUtils.getString(mSp, getSPKey()).split(DIVIDER_KEY)
return if (list.size == 1 && list[0].isEmpty()) null else ArrayList(list)
}
fun getRawString(): String = SPUtils.getString(mSp, getSPKey())
fun contains(key: String): Boolean {
return getAll()?.contains(key) == true
}
fun deleteAll() {
SPUtils.setString(mSp, getSPKey(), "")
}
open fun getMaxSize(): Int = -1
abstract fun getSPKey(): String
companion object {
private const val DIVIDER_KEY = "<-||->"
}
}