Search code examples
androidandroid-fragmentsparameter-passingbundlegetter-setter

Why I have to pass Bundle to Fragment in Android


We usually use below style when we pass parameter to the fragment

public static MyFragment newInstance() {
    MyFragment fragment = new MyFragment();
    String myVariable = "My variable string";
    Bundle bundle = new Bundle();
    bundle.putString("myVariable", myVariable);
    fragment.setArguments(bundle);
    return fragment;
}

What happens when we use getter setter method:

private String myVariable;
public String getMyVariable() {
    return myVariable;
}
public void setMyVariable(String myVariable) {
    this.myVariable = myVariable;
}
public static MyFragment newInstance() {
    MyFragment fragment = new MyFragment();
    String passVariable = "My variable string";
    fragment.setMyVariable(passVariable);
    return fragment;
}


public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    String passVariable = getMyVariable();

}

When I test with the second way, there is no problem occurs. So why we have to use the first way?

I also saw the post "Why use bundle to pass data to fragment?". They said "it's easier for the system to restore its values when the fragment is re-instantiated" But I tested in case the fragment is popped from stack, the variable is still remained.


Solution

  • If the framework needs to recreate your fragment, the data you have set with your second setter method is lost.

    Argument bundles persist to recreated fragments.