'How to save the data on a fragment while switching between them

I have a app with a main activity and fragments. My fragments work but when I switch between them, they refresh and create a new fragment when I switch back. I want the data to save when I switch back and forth, but I can't figure out how to use a bundle to save the values.

This is the code that controls switching between fragments: `private NavigationBarView.OnItemSelectedListener navListener = new BottomNavigationView.OnItemSelectedListener() {

            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                Fragment selectedFragment = null;//used to default to home
                if(item.getItemId() == R.id.nav_home){
                    selectedFragment = new HomeFragment();

                }else if(item.getItemId() == R.id.nav_input){
                    //selectedFragment = new InputFragment();
                    if((InputFragment) getSupportFragmentManager().findFragmentByTag("input_tag") != null){

                        selectedFragment = (InputFragment) getSupportFragmentManager().findFragmentByTag("input_tag");

                    }else{
                        selectedFragment = new InputFragment();
                    }




                }else if(item.getItemId() == R.id.nav_balance){
                    selectedFragment = new BalanceFragment();

                }else if(item.getItemId() == R.id.nav_calendar) {
                    selectedFragment = new CalendarFragment();
                }
                if(selectedFragment == null) selectedFragment = new HomeFragment();
                
                getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                        selectedFragment, "input_tag").commit();

                return true;
            }
        };

}`

I tried reformatting it, and looked through Android Studio forums, but I can't seem to find anything helpful to resolving this problem. I unsuccessfully tried to use tags to save a fragment, but it didn't retain the data. I also tried to use savedInstanceState but it did not work. Any help or directions to start in would be greatly appreciated.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source