Issue
I am trying to figure out how to correctly use the viewLifecycleOwner in MainActivity, I have read and been told lifecycles are used with fragments. However, I am not implementing fragments in my app. When adding observers in the code, I am using "this" in place of viewLifecycleOwner. This would not rise any errors, but will eventually not work as it doesn't bind data properly in the virtual device (when running the app, it only displays a blank page for the app without data or images). So far, what I have in MainActivity is the following code.
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(this, Observer { newRevenue ->
binding.revenueText.text = newRevenue.toString()
})
viewModel.drinksSold.observe(this, Observer { newAmount ->
binding.amountSoldText.text = newAmount.toString()
})
}
}
Solution
After EpicPandaForce's comment, I focused on whether I was correctly binding the data and images. I realized I was not. I was mistakenly binding revenue and amountSold as texts. I was also trying to set newRevenue and newAmount to strings. Revenue and amountSold were supposed to be passed as Integers. The following code is the correct one.
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(this, Observer { newRevenue ->
binding.revenue = newRevenue
})
viewModel.drinksSold.observe(this, Observer { newAmount ->
binding.drinkSold = newAmount
})
}
}
Answered By - stcol
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.