Android room+协程 实现保存搜索记录
添加依赖
implementation "androidx.room:room-runtime:2.3.0"
implementation "androidx.room:room-ktx:2.3.0"
kapt "androidx.room:room-compiler:2.3.0" // use kapt for Kotlin
//lifecycle
implementation "androidx.lifecycle:lifecycle-runtime-ktx:2.3.1"
//协程相关
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.9"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.9"
定义数据表实体类
@Entity(tableName = "history")
class HistoryEntity {
@PrimaryKey(autoGenerate = true)
var id: Int = 0
@ColumnInfo(name = "type")
var type: Int = 0
@ColumnInfo(name = "query")
var query: String = ""
}
定义数据库操作Dao类
@Dao
interface HistoryDao {
@Insert
suspend fun insert(vararg users: HistoryEntity)
@Delete
suspend fun delete(user: HistoryEntity)
@Delete
suspend fun deleteAll(users: MutableList<HistoryEntity>)
@Update
suspend fun updateHistory(user: HistoryEntity)
@Query("SELECT * FROM history")
suspend fun getAllHistory():MutableList<HistoryEntity>
}
定义数据库
//version 表示数据库版本号
@Database(entities =[HistoryEntity::class],version = BuildConfig.VERSION_CODE)
abstract class AppDataBase : RoomDatabase() {
// 必须包含一个具有0个参数且返回带@Dao注释的类的抽象方法
abstract fun userHistory(): HistoryDao
companion object {
private var appDataBase: AppDataBase? = null
fun getInstance(context: Context): AppDataBase? {
if (appDataBase == null) {
synchronized(AppDataBase::class.java) {
appDataBase = Room.databaseBuilder(context.applicationContext,AppDataBase::class.java,"my_database").build()
}
}
return appDataBase!!
}
}
}
配合协程使用
数据库的增删改查等操作避免放到UI线程中使用
搜索所有历史记录
val historyDao=AppDataBase.getInstance(this)?.userHistory()
//获取所有历史记录
lifecycleScope.launch(Dispatchers.Main) {
withContext(Dispatchers.IO){
list.addAll(historyDao?.getAllHistory()!!)
}
adapter.notifyDataSetChanged()
}
搜索添加搜索记录
//添加搜索记录
btnSearch.setOnClickListener {
if(etSearch.text.toString().trim().isEmpty()){
return@setOnClickListener
}
lifecycleScope.launch(Dispatchers.IO){
val bean=HistoryEntity()
bean.query=etSearch.text.toString()
bean.type=1
historyDao?.insert (bean)
list.add(bean)
withContext(Dispatchers.Main){
adapter.notifyDataSetChanged()
}
}
}
删除记录
//长按删除
adapter.setOnItemLongClickListener { _, _, position ->
lifecycleScope.launch(Dispatchers.IO){
val bean= list[position]
historyDao?.delete (bean)
list.removeAt(position)
withContext(Dispatchers.Main){
adapter.notifyDataSetChanged()
}
}
return@setOnItemLongClickListener true
}
完整代码
class HistoryActivity : AppCompatActivity() {
private val list = mutableListOf<HistoryEntity>()
private var adapter:HistoryAdapter=HistoryAdapter(list)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_history)
val recyclerview=findViewById<RecyclerView>(R.id.recyclerview)
val etSearch=findViewById<EditText>(R.id.et_search)
val btnSearch=findViewById<TextView>(R.id.btn_search)
recyclerview.layoutManager=LinearLayoutManager(this)
val historyDao=AppDataBase.getInstance(this)?.userHistory()
recyclerview.adapter=adapter
//获取所有历史记录
lifecycleScope.launch(Dispatchers.Main) {
withContext(Dispatchers.IO){
list.addAll(historyDao?.getAllHistory()!!)
}
adapter.notifyDataSetChanged()
}
//添加搜索记录
btnSearch.setOnClickListener {
if(etSearch.text.toString().trim().isEmpty()){
return@setOnClickListener
}
lifecycleScope.launch(Dispatchers.IO){
val bean=HistoryEntity()
bean.query=etSearch.text.toString()
bean.type=1
historyDao?.insertAll (bean)
list.add(bean)
withContext(Dispatchers.Main){
adapter.notifyDataSetChanged()
}
}
}
//长按删除
adapter.setOnItemLongClickListener { _, _, position ->
lifecycleScope.launch(Dispatchers.IO){
val bean= list[position]
historyDao?.delete (bean)
list.removeAt(position)
withContext(Dispatchers.Main){
adapter.notifyDataSetChanged()
}
}
return@setOnItemLongClickListener true
}
}
}