I have my fragment home view model, and I want to set inside this viewmodel a variable in order to pass it inside another fragment. I have done all the stuff for view model, but when I start my emulator the app dont show anything...
HomeViewModel:
class HomeViewModel: ViewModel() {
val text = MutableLiveData<String>()
fun setText(string: String) {
text.value = string
}
}
Home fragment (where i set the value of variable):
private var valueFromHome = "ABCDEFG"
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
// API CALL
binding.buttonHomeFragmentApiCall.setOnClickListener {
this.context?.let { getRandomComputerDetails(it, myResultListener) }
// SET OF VALUE FOR VARIABLE IN VIEW MODEL
homeViewModel = ViewModelProvider(requireActivity()).get(HomeViewModel::class.java)
homeViewModel.setText(valueFromHome)
}
}
Info fragment (where i read from view model):
class InfoFragment : Fragment() {
private var _binding: FragmentInfoBinding? = null
private lateinit var binding: FragmentInfoBinding
private lateinit var homeViewModel: HomeViewModel
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
binding = FragmentInfoBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
// I READ HERE FROM VIEW MODEL
homeViewModel = ViewModelProvider(this).get(HomeViewModel::class.java)
homeViewModel.text.observe(viewLifecycleOwner, Observer {
binding.infoFragmentTextView.text = it
})
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
}
So, in the info fragment where i set text, precisely binding.infoFragmentTextView.text = it
once i start the emulator, nothing actual is shown (Instead I'm expecting a string in the fragment (ABCDEFG). Why?
CodePudding user response:
You're using a different scope for each of your view models. One is correctly scoped to the activity and the other is scoped to your fragment.
If you want to refer to the same view model, you'll need to use ViewModelProvider(requireActivity())
in both cases.