I am trying to show a Toast message in a Fragment using MutableLiveData Event, but I cannot show the toast message, error is
None of the following functions can be called with the arguments supplied. makeText(Context!, CharSequence!, Int) defined in android.widget.Toast makeText(Context!, Int, Int) defined in android.widget.Toast
ViewModel
class AddProductViewModel (
private val repository: ProductRepository,
private val context: Context
): ViewModel(), Observable {
private val statusMessage = MutableLiveData<Event<String>>()
val message : LiveData<Event<String>>
get() = statusMessage
}
Fragment
class AddProductFragment: Fragment() {
private lateinit var binding: AddProductBinding
private lateinit var addProductViewModel: AddProductViewModel
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = DataBindingUtil.inflate(inflater, R.layout.add_product, container, false)
val dao = SubscriberDatabase.getInstance(requireActivity().applicationContext).productDAO
val repository = ProductRepository(dao)
val factory = AddProductViewModelFactory(repository, requireActivity().applicationContext)
addProductViewModel = ViewModelProvider(this, factory).get(AddProductViewModel::class.java)
binding.addProductViewModel = addProductViewModel
binding.lifecycleOwner = this
val view = binding.root
addProductViewModel.message.observe(viewLifecycleOwner, Observer {
it.getContentIfNotHandled()?.let {
***Error is on this line***
Toast.makeText(viewLifecycleOwner,it, Toast.LENGTH_LONG).show
}
})
return view
}
}
How can I correct this please thanks in advance
Thanks R
Please use next line for showing a Toast
message in a Fragment
:
Toast.makeText(context, it, Toast.LENGTH_LONG).show()
You use viewLifecycleOwner
as the first argument but it should be a Context
.