简体   繁体   中英

Android ViewModel not getting Selected Item from BackStackEntry

I have a map fragment that can be accessed from the bottom nav bar. I also want to be able to access it from a click on my recyclerview (if it is clicked from the recycler view, display the location from the recyclerview). To do this, I've attempted to check the backstack to see if the listfragment exists. I can't get it to work though, can someone see the issue with my code?

ViewModel:

    private final MutableLiveData<Fish> selected = new MutableLiveData<Fish>();

public void select(Fish item) {
    selected.setValue(item);
}

public LiveData<Fish> getSelected() {
    return selected;
}


public MapViewModel(Application application){
    super(application);
}

ListFragment(select is in onclick method):

mMapViewModel = ViewModelProviders.of(this).get(MapViewModel.class);
Log.d("view-click", String.valueOf(fish.getLocation()));

                mMapViewModel.select(fish);
                Navigation.findNavController(view).navigate(R.id.action_fishListFragment_to_mapFragment2);

MapFragment:

NavController navController = NavHostFragment.findNavController(this);
    NavBackStackEntry backStackEntry = navController.getBackStackEntry(R.id.fishListFragment);

    mMapViewModel = new ViewModelProvider(backStackEntry).get(MapViewModel.class);
    mMapViewModel.getSelected().observe(backStackEntry, list -> {
        Log.d("MAPFRAGMENT",list.getLocation() + "");
    });

I get no errors, but I also don't get the MAPFRAGMENT log in the logcat window. I've verified that my logcat is working, and that the onclick method is in fact setting the value in the viewmodel.

ViewModelProviders.of(this) is associating the ViewModel with this - your Fragment itself, not the NavBackStackEntry (which is a whole separate layer above the Fragment layer).

Instead, you'll want to use navController.getCurrentBackStackEntry() with new ViewModelProvider() in your FishListFragment to associate the ViewModel with the NavBackStackEntry that you're later accessing in the MapFragment:

NavController navController = Navigation.findNavController(view);
NavBackStackEntry currentBackStackEntry = navController.getCurrentBackStackEntry();
mMapViewModel = new ViewModelProvider(currentBackStackEntry).get(MapViewModel.class);
Log.d("view-click", String.valueOf(fish.getLocation()));

mMapViewModel.select(fish);
navController.navigate(R.id.action_fishListFragment_to_mapFragment2);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM