I user MVVM and RecyclerView in this app so the recycle view show the list perfectly but when i add the view model to adapter i get an error in the logcat
Your activity is not yet attached to the Application instance. You can't request ViewModel before onCreate call.
i am new in this MVVM and i know is this possible or is any other way to do this
this is my adapter class with the viewHolder
class KeefAdapter : RecyclerView.Adapter<KeefViewHolder>()
{ var dataOfAllKeef = listOf()
init {
dataOfAllKeef = arrayListOf("Marijuwana" , "Bango" , "Weed" , "Hash")
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): KeefViewHolder {
lateinit var binding: KeefSingleItemBinding
binding = DataBindingUtil.inflate(LayoutInflater.from(parent.context) , R.layout.keef_single_item , parent , false)
val viewModel:OrderYourKeefViewModel = ViewModelProvider(OrderYourKeef()).get(OrderYourKeefViewModel::class.java)
binding.orderViewModelWithSingle = viewModel
viewModel.count.observe(OrderYourKeef(), Observer { newCountOfHash->
binding.root.theCountOfHash.text = newCountOfHash.toString()
})
return KeefViewHolder(binding.root)
}
override fun getItemCount() = dataOfAllKeef.size
override fun onBindViewHolder(holder: KeefViewHolder, position: Int) {
val item = dataOfAllKeef[position]
holder.keefName.text = item
if (item.equals("Marijuwana"))
{
holder.keefImage.setImageResource(R.mipmap.marijuana)
}else if (item.equals("Bango"))
{
holder.keefImage.setImageResource(R.mipmap.bango)
}else if (item.equals("Weed"))
{
holder.keefImage.setImageResource(R.mipmap.weed)
}else if (item.equals("Hash"))
{
holder.keefImage.setImageResource(R.mipmap.hashesh)
}
}
}
class KeefViewHolder(itemView:View) : RecyclerView.ViewHolder(itemView) {
var keefName:TextView = itemView.keefName
var keefImage: ImageView = itemView.keefImage
var increase: Button = itemView.increaseTheCount
var decrease: Button = itemView.minusTheCount
var theCountOfKeef: TextView = itemView.theCountOfHash
}