3

I have my FragmentActivity :

public class FragmentActivity extends FragmentActivity
{
    // ...
    protected void onCreate(Bundle savedInstanceState) {
         if (savedInstanceState != null) {
             myFragment = (MyFragment) getSupportFragmentManager().getFragment(
            savedInstanceState, MyFragment.class.getName());
         }
         else {
             myFragment = new Fragment(myObject);
         }
    }
}

And in my Fragment :

public class MyFragment extends Fragment
{
    public MyFragment(myObject) {
        super();
        this.myObject = myObject;
        setRetainInstance(true);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        MyDAO myDAO = new MyDAO (myObject);
    }
}

Everything is working except when i close my application, do some stuff (my application enters in background) and then relaunch my application. I get a NullPointerException on

MyDAO myDAO = new MyDAO (myObject);

where myObject is null.

The savedInstanceState is called ... i don't understand how this is working.

TY

Aximem
  • 714
  • 8
  • 27
  • May be this could help you. http://stackoverflow.com/questions/8474104/android-fragment-lifecycle-over-orientation-changes – Chintan Soni Apr 25 '13 at 13:06

1 Answers1

2

The system is killing your process and the instance of myObject is being garbage collected. Setting the instance to be retained is only helpful between orientation changes, but keep in mind that your app running in background may be killed when the system runs out of memory. Pass this variable as an argument instead. It's important to implement Parcelable or Serializable on MyDAO class.

PS.: You need to have an empty constructor for your fragment because the system recreates its instance when your activity is recreated:

public MyFragment() {

}


public MyFragment(myObject) {
    super();
    setRetainInstance(true);
    Bundle args = new Bundle();
    args.putParcelable("myObject", myObject);
    setArguments(args);
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    myObject = getArguments().getParcelable("myObject");
    MyDAO myDAO = new MyDAO (myObject);
}
Flávio Faria
  • 6,575
  • 3
  • 39
  • 59
  • TY Flavio, this is working, my application is launched again thanks to bundle and Parcelable. – Aximem Apr 25 '13 at 15:47