Issue
I am having an error using Observer and viewLifecycleOwner in my android project. It throws a "Unresolved reference: viewLifecycleOwner" error and I have no clue why. I verified I had the imports
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
And the dependency:
implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
I have tried to Invalidate Caches / Restart... solution found in GitHub. But the error persists. Thanks to anyone who can help me.
class MainActivity : AppCompatActivity() {
private lateinit var viewModel: DrinkViewModel
// Contains all the views
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
viewModel = ViewModelProvider(this).get(MyViewModel::class.java)
// Use Data Binding to get reference to the views
binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
binding.drinkButton.setOnClickListener {
onDrinkClicked()
}
viewModel.revenue.observe(viewLifecycleOwner, Observer { newRevenue ->
binding.revenueText.text = newRevenue.toString()
})
viewModel.drinksSold.observe(viewLifecycleOwner, Observer { newAmount ->
binding.amountSoldText.text = newAmount.toString()
})
binding.drinkButton.setImageResource(viewModel.currentDrink.value!!.imageId)
}
}
Solution
getViewLifecycleOwner() is method to represent fragment's lifeCycle. You can't call it from activiy scope. You can just use this
or if you are familiar with coroutines, you can use lifeCycleScope .
Answered By - Berkay Kireçci
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.