jeff_bordon
jeff_bordon

Reputation: 412

Fragment initialization with complex object

I need to pass a complex object including methods and fields to a Fragment. The complex object implements an Interface IComplexObject which is then called by the Fragment, so in my Fragment the complex object itself is not visible.

For creating Instances of the Fragment I use the following code, inspired by this post:

public class SimpleContentFragment extends Fragment {
    private IComplexObject complexObject;

    protected static SimpleContentFragment newInstance(IComplexObject complexObject) {

        SimpleContentFragment f = new SimpleContentFragment();
        f.complexObject = complexObject;

        return f;
    }

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        complexObject.doSomeThings();
    }

}

This generally works like expected, however, in some cases when I try to access complexObject from the Fragment's onCreateView I get a NullPointerException.

I have experienced this Exception only on a few older devices and some Kindle devices.

Any ideas what I am doing wrong? How I can pass the object into my Fragment?

Upvotes: 0

Views: 1400

Answers (2)

Divers
Divers

Reputation: 9569

It happens because your fragment can completely recreated( for example during orientation change), that's why you have NEW object of fragment with all fields equals null.

Mark your object as Parcelable will not help if you object contains other objects, which classes is not under your control ( e.g. library's classes)

You should look in side of setRetainInstance method. It will help.

Upvotes: 1

JafarKhQ
JafarKhQ

Reputation: 8734

1- make your IComplexObject Parcelable.
see those examples 1, 2 and 3

2- but your object in fragment args

protected static SimpleContentFragment newInstance(IComplexObject complexObject) {

        SimpleContentFragment f = new SimpleContentFragment();

        Bundle args = new Bundle();
        args.putParcelable("key_complexObject", complexObject);
        f.setArguments(args);

        return f;
 }

3- on onCreate() function get your object form args

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Bundle bundle = getArguments();
    this.complexObject = bundle.getParcelable("key_complexObject");
}

Upvotes: 1

Related Questions