0

I have Fragment A that lets the user access Fragment B by the click of a button, when an action is performed on B, user is redirected to Fragment C to retrieve a last bit of information before returning to A. (A -> B -> C -> A).

After doing this, if I open my Navigation Drawer and click on the Fragment I am currently on (A), its contents are gone, only the Drawer itself remains.

I can't seem to explain the reason behind this.

Here is how I conserve my Navigation Drawer's Fragment states:

  // User clicks on an item in Nav. Drawer, call this method
  private Fragment checkFragmentState(int itemId) {
    Fragment fragment = null;

    switch (itemId) {
        // HOME
        case R.id.nav_home:
            if (home == null) {
                fragment = new Home();
                home = fragment;
            } else
                fragment = home;
            break;
        // SEARCH CARD
        case R.id.nav_searchCard:
            if (searchCard == null) {
                fragment = new SearchCard();
                searchCard = fragment;
            } else
                fragment = searchCard;
            break;        
    }
    return fragment;
}

I call this method when my user clicks on an element in the Drawer, basically it checks if the Fragment has already been created, if so, it saves the currently existing one and uses it to be displayed.

What could cause this odd behavior?

  • Check [this](http://stackoverflow.com/questions/15392261/android-pass-dataextras-to-a-fragment). – AlphaQ Dec 20 '16 at 20:31

1 Answers1

0

Just launch a new instance each time

// User clicks on an item in Nav. Drawer, call this method
private Fragment checkFragmentState(int itemId) {

    Fragment fragment = null;

    switch (itemId) {
        case R.id.nav_home:
            fragment = new Home();
            break;
        case R.id.nav_searchCard:
            fragment = new SearchCard();
            break;    
        default:
            fragment = new Fragment();    
    }

    return fragment;
}
Reaz Murshed
  • 23,691
  • 13
  • 78
  • 98
  • Let's say I want to keep what the user has previously inputted in one fragment, how can that be done if I launch a new instance each time? EDIT: That does solve my problem, could you explain to me what I was doing wrong? –  Dec 20 '16 at 20:11
  • You can put them in a `SharedPreference` or in a Sqlite database. – Reaz Murshed Dec 20 '16 at 20:13