2

I have BottomNavigationBar with five tabs. In that fragment, I'm loading data from the server. My issue is that Fragment each time loads data on changing tab. I don't want to load data every time.

I know it can be possible using onSaveInstanceState(), but it is useful to save a small amount of data.

And one thing, There is all fragments in-app, so can't get any solution for my problem. Any help would be appreciated

MainActivity:

 private boolean loadFragment(Fragment fragment) {
    if (fragment != null) {
        getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.fragmentContainer, fragment)
                .commit();
        return true;
    }
    return false;
}
Shalu T D
  • 3,921
  • 2
  • 26
  • 37
Hetal
  • 471
  • 4
  • 14

1 Answers1

3

Do You write Your application in MVVM architectural pattern? If so I think You can use Shared ViewModel.
Android docs. Share data between fragments
Stack Overflow: Sharing data between fragments using new architecture component ViewModel
I think this might help You. If You load data in ViewModel class You can use it in all fragments even when Your app stoped You don't have to load it again.

iknow
  • 8,358
  • 12
  • 41
  • 68
  • Thanks for the reply! No I am not using MVVM architectural, but using example in this https://stackoverflow.com/questions/44272914/sharing-data-between-fragments-using-new-architecture-component-viewmodel, where I should load my data from server and all that stuff? – Hetal Jul 10 '20 at 10:50
  • @Hetal Maybe You can load your data to the SQLite database? If You load it once You can use that data in the whole app. [This question might help You.](https://stackoverflow.com/questions/22640519/best-practice-for-loading-data-from-server-android-app) – iknow Jul 10 '20 at 11:24