Search code examples
androidandroid-fragmentsnavigation-drawerbundle

Is possible send bundle args to ALL fragments using Navigation Drawer Layout?


I have a navigation drawer with fifteen fragments to be switched between them, I want a common data to exist between this fragment, so I only need to pull it from the database once and use it in all my fragments, is there any way to send a Bundle for all my Navigation fragments?

Currently, I can only send to the first fragment (the one at the beginning, as follows in the code below), I want to send to all fragments of the navigation view ... Should I use SharedPreferences? but the data is always changing (whenever the app opens).

NavigationView navigationView = findViewById(R.id.nav_view);
        mAppBarConfiguration = new AppBarConfiguration.Builder(R.id.nav_home, R.id.nav_cad_bov, R.id.nav_attBoi, R.id.nav_acomp,
                R.id.nav_manejo, R.id.nav_patology, R.id.nav_desp, R.id.nav_ven, R.id.nav_meus_anu,
                R.id.nav_meus_anun_ed, R.id.nav_cap, R.id.nav_comp, R.id.nav_tuto, R.id.nav_editInfo, R.id.nav_logout).setOpenableLayout(drawer)
                .build();
        Bundle bundle = new Bundle();
        bundle.putString("amount", "Katinguele"); // Send to start fragment, i need send to ALL fragments
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
        navController.setGraph(R.navigation.mobile_navigation, bundle);

        NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
        NavigationUI.setupWithNavController(navigationView, navController);

Solution

  • You can achieve this using a sharedViewModel across all the fragments.

    public class SharedtViewModel extends ViewModel {
        private MutableLiveData<String> amount;
    
        public void init()
        {
            amount = new MutableLiveData<>();
        }
    
        public void setAmount(String amount)
        {
            amount.setValue(amount);
        }
       
        public LiveData<String> getAmount() {
            return amount;
        }
    }
    

    Set the amount value from your Activity.

    SharedViewModel viewModel = ViewModelProviders.of(this).get(SharedViewModel.class);
    viewModel.setAmount(amount);
    

    At the end, in every Fragment, you can observe it as follows:

    public class FragmentA extends Fragment {
        public void onActivityCreated() {
            SharedViewModel model = ViewModelProviders.of(getActivity()).get(SharedViewModel.class);
            model.getAmount().observe(this, { amount ->
               // Anything here
            });
        }
    }