Reputation: 856
I face this problem after migrating my project to androidx
. It all worked like a charm before the migration (i had to migrate my project) but now i stand before this weird problem that didnt exist 10min earlier.
Scenario:
Fragment 1 contains a listview of items and when user click on item i call my viewmodels setvalue()
method and then fragment 2 appears to show the item user clicked on and for this i call my viewmodels getvalue()
. The scenario is very simple.
Fragment 1:
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
viewModel.getClickedSong().setValue(viewModel.getSongs().getValue().get(position));
Viewmodel:
public MutableLiveData<Song> getClickedSong() {
if (clickedSong == null) {
clickedSong = new MutableLiveData<>();
}
return clickedSong;
}
Fragment 2:
viewModel.getClickedSong().observe(this, new Observer<Song>() {
@Override
public void onChanged(Song song) {
mySong = song;
I also tried: mySong = viewModel.getClickedSong().getValue()
but this also returns null.
Upvotes: 6
Views: 8926
Reputation: 856
After hours of researching, testing etc. the fix was quite simple.
I changed this line of code:
viewModel = ViewModelProviders.of(this).get(SharedViewModel.class);
To this:
viewModel = ViewModelProviders.of(getActivity()).get(SharedViewModel.class);
Upvotes: 6