Android jetpack room+协程 实现保存搜索记录

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
        }

    }
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值