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

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.

Related

fragment bottom navigation bar clickable one time selected item

When I click again to any item, same fragment view reloading every time. But I wanna do bottom navigation bar item one time clickable. how can i do this?
This is MainActivity.java codes
navigationMenu=findViewById(R.id.navigation);
navigationMenu.setOnNavigationItemSelectedListener(navListener);
//navigationMenu.getMenu().getItem(2).setIcon(R.drawable.arrow_down);
//I added this if statement to keep the selected fragment when rotating the device
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new UserHomeFragment()).commit();
}
This is click listener codes
private BottomNavigationView.OnNavigationItemSelectedListener navListener =
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment selectedFragment = null;
switch (item.getItemId()) {
case R.id.navigation_home:
selectedFragment = new UserHomeFragment();
break;
case R.id.navigation_works:
selectedFragment = new UserWorksFragment();
break;
case R.id.navigation_completed_works:
selectedFragment = new UserCompletedFragment();
break;
case R.id.navigation_profile:
selectedFragment = new UserAccountFragment();
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
selectedFragment).commit();
return true;
}
};

Bottom navigation bar stop a fragment running when another one is opened

So I have no idea how to do this and even where to start, so if someone would be patient enough to explain how to do this I would be appreciated.
I already looked up on google but what I found was too difficult to understand ( and I am pretty sure that it can be done way more easily.
I have 4 fragments (4 tabs on a bottom navigation bar) and I want to have only 1 running at the time.
Now, I am pretty sure that I should use FragmentManager but I don't really know how to start to implement in my program.
Do I have to write all the FragmentTransaction code in the mainActivity? and after that how to keep goin? Is there a example code by any chance?
Disclaimer: I am a total noob in the android studio environment and I am also a student and I almost do everything as a school project.
You Can try this in your code. On the onNavigationItemSelected
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment fragment = null;
switch (item.getItemId()) {
case R.id.navigation_home:
fragment = new HomeFragment();
break;
case R.id.navigation_dashboard:
fragment = new DashboardFragment();
break;
case R.id.navigation_notifications:
fragment = new NotificationsFragment();
break;
case R.id.navigation_profile:
fragment = new ProfileFragment();
break;
}
return loadFragment(fragment);
}
private boolean loadFragment(Fragment fragment) {
//switching fragment
if (fragment != null) {
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragment_container, fragment)
.commit();
return true;
}
return false;
}
I hope this can help You!
Thank You.

How to get last Fragment used when pressing back button

I have a simple fragment with this code:
private BottomNavigationView.OnNavigationItemSelectedListener navListener =
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
Fragment selectedFragment= null;
switch (menuItem.getItemId()){
case R.id.nav_home:
selectedFragment= new HomeFragment();
setTitle("Beranda");
break;
case R.id.nav_message:
selectedFragment= new MessageFragment();
setTitle("Pesan");
break;
case R.id.nav_transaction:
selectedFragment= new TransactionFragment();
setTitle("Transaksi");
break;
case R.id.nav_profile:
selectedFragment= new ProfileFragment();
setTitle("Profil");
if(sessionLevel.equals("admin")){
setTitle("Admin");
}
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, selectedFragment).commit();
return true;
}
};
Most of the fragment are just some kind of holder for Intent Activity. And the Activity itself doesnt have some fancy code.
The problem is that when i do Intent on Profile menu and then press back, the fragment shown is HomeActivity but the selected button is Profile.
I dont know about the other 2 fragment since im not there yet, but probably they do the same thing.
You can do this like the following:
#Override
public void onBackPressed() {
super.onBackPressed();
Fragment frag = YourActivity.this.getSupportFragmentManager().findFragmentById(R.id.fragment_container);
if(frag!=null && frag instanceof yourFragment)
{}
}
The following will give you count
int count = getSupportFragmentManager().getBackStackEntryCount();
You can make condition, If count is great than 1 then have more than 1 fragments else you have atleast 1 fragment and that will be last fragment. If count 0 then no more fragment available on stack as all have been poped out of stack.
Create an interface:
public interface IOnBackPressed {
boolean onBackPressed();
}
In Fragment implement IOnBackPressed like:
public class FAQFragment extends Fragment implements IOnBackPressed {
public boolean onBackPressed() {
return false
}
}
On Main Activity Backpress use
#Override
public void onBackPressed(){
if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
getSupportFragmentManager().popBackStack();
}
}

NullPointerException when using BottomNavigationView

// I learned android studio about BottomNavigationView, but I have a problem like this ... please help me :(
// Caused by: java.lang.NullPointerException: Attempt to invoke
virtual method 'void
android.support.design.widget.BottomNavigationView.setOnNavigationItemSelectedListener(android.support.design.widget.BottomNavigationView$OnNavigationItemSelectedListener)'
on a null object reference// eror logcat
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
BottomNavigationView bottomNav = findViewById(R.id.bottom_navigation);
bottomNav.setOnNavigationItemSelectedListener(navListener);
}
private BottomNavigationView.OnNavigationItemSelectedListener navListener =
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
Fragment selectedFragment = null;
switch (menuItem.getItemId()) {
case R.id.nav_home:
selectedFragment = new HomeFragment();
break;
case R.id.nav_search:
selectedFragment = new SearchFragment();
break;
case R.id.nav_filter:
selectedFragment = new PesananFragment();
break;
case R.id.nav_notifikasi:
selectedFragment = new NotificationFragment();
break;
case R.id.nav_akun:
selectedFragment = new AccountFragment();
break;
}
assert selectedFragment != null;
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, selectedFragment).commit();
return true;
}
};
}
It looks like a problem with the initial bottomNav stationing.
Maybe try to put explicit casting like:
BottomNavigationView bottomNav=(BottomNavigationView)findViewById(R.id.bottom_navigation);
If that does not work check the BottomNavigationView implementation requirements.
You can use android studio to create a activity that already has a Bottom navigation.

Fragment Transaction shows Tabs Fragment below

I'm making an app that has launches with a Swiping Tabs Fragment, but I also want to have a Preferences menu using Fragment Transaction. When I press the Settings button in my app, the preferences menu does appear and is interactive, but the layout seems to be transparent showing the Tabs below. Is there anything that can be done to fix this, or is there a better method?
Code that calls the Preferences Menu from the Options:
public boolean onOptionsItemSelected(final MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
getFragmentManager().popBackStackImmediate();
break;
case R.id.logout:
FirebaseAuth.getInstance().signOut();
finish();
startActivity(new Intent(this, Activity_Main.class));
break;
case R.id.action_settings:
getFragmentManager().beginTransaction()
.replace(android.R.id.content, new Fragment_Settings()).addToBackStack(null)
.commit();
break;
}
return true;
}
Code that calls Tabs Fragments:
public class TabsPagerAdapter extends FragmentPagerAdapter {
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public android.support.v4.app.Fragment getItem(int index) {
switch (index) {
case 0:
// Top Rated fragment activity
return new Fragment_Flower();
case 1:
// Games fragment activity
return new Fragment_Overview();
}
return null;
}
#Override
public int getCount() {
// get item count - equal to number of tabs
return 2;
}
}
Initialising Transaction in onCreate:
startService(new Intent(this, SensorListener.class));
if (b == null) {
// Create new fragment and transaction
Fragment newFragment = new Fragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
//Replace whatever is in the fragment_container view with this
// fragment,
// and add the transaction to the back stack
transaction.replace(android.R.id.content, newFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
}
Any help will be greatly appreciated!
Just set background color in your layout file. It may avoid transparent backgound.

Categories