Search code examples
androidandroid-fragmentsandroid-bundle

The correct way and place to restore bundle information on a fragment?


I have seen Bundles restored in several of the Android callback methods, but in many cases there is manual creation and setting of Bundles as on the developers website, in this case from an external message on Fragment creation:

public static DetailsFragment newInstance(int index) {
    DetailsFragment f = new DetailsFragment();

    // Supply index input as an argument.
    Bundle args = new Bundle();
    args.putInt("index", index);
    f.setArguments(args);

    return f;
}

In this other question, for example, bundle data is restored in the onCreateView() method.

public class Frag2 extends Fragment {

    public View onCreateView(LayoutInflater inflater,
        ViewGroup containerObject,
        Bundle savedInstanceState){
        //here is your arguments
        Bundle bundle=getArguments(); 

        //here is your list array 
        String[] myStrings=bundle.getStringArray("elist");   
    }
}

I am a bit confused about the Bundle data supplied with each callback method VS "other bundles":

Bundle bundle=getArguments(); 

and the correct way and place to retrieve these different types of bundled data.

Thanks in advance!


Solution

  • The two ways described above are exactly the correct way to

    • initialize a new instance of the Fragment and pass the initial parameters.
    • retrieve the initial parameters in the Fragment.

    In other words, you're on the right track! It should work, and you should be pleased with yourself :)

    EDIT:

    • The Bundle can be retrieved in either onCreateView() or onCreate(). I'd prefer onCreate(), as it represents the creation of the Fragment instance and is the right place for initialization.
    • There is always one and only one Bundle instance retrieved by the call to getArguments(), and this Bundle instance contains all of your ints, Strings, whatever.