I have RecycerView Adapter and checkbox in onBindViewHolder function. I need to save state "checked" or "unchecked" of checkbox if i exit app. I have tried SharedPreferences, but i cant use it in Adapter, how can i do this?
Code Adapter:
private lateinit var databaseReferenceFavorite: DatabaseReference
private lateinit var id: String
inner class ViewHolder(val binding: CarsListBinding): RecyclerView.ViewHolder(binding.root)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder(CarsListBinding.inflate(LayoutInflater.from(parent.context), parent, false))
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
with(holder) {
with(carsList[position]) {
Picasso.with(itemView.context).load(image).into(binding.ivCar)
binding.tvCar.text = this.name
binding.cbFavorite.setOnCheckedChangeListener { checkBox, isChecked ->
if (checkBox.isChecked) {
val image: String = this.image
val name: String = this.name
databaseReferenceFavorite = FirebaseDatabase.getInstance().reference
.child("Cars")
.child("Favorite Item")
val favorite = Favorite(name, image)
id = databaseReferenceFavorite.push().key.toString()
databaseReferenceFavorite.child(id).setValue(favorite)
Toast.makeText(itemView.context, "Item added to favorite", Toast.LENGTH_SHORT).show()
} else {
databaseReferenceFavorite = FirebaseDatabase.getInstance().getReference("Cars").child("Favorite Item").child(id)
databaseReferenceFavorite.removeValue()
Toast.makeText(itemView.context, "Item removed from favorite", Toast.LENGTH_SHORT).show()
}
}
}
}
}
override fun getItemCount(): Int {
return carsList.size
}
Aucun commentaire:
Enregistrer un commentaire