0

I'm using a Fragment inside an Activity. The Fragment has an OnInitListener interface, in order to pass data to the host Activity, which is called inside it's onCreate() method. The issue is that some times (generally when the screen is locked and unlocked) I get a NullPointerException from an object that it is initialled on the Activity#onCreate Here's the code:

// Activity
public void onCreate() {
    super.onCreate();
    // ...some code...

    myObject = new MyObject();
}

@Override
public void onInit(ObjectProperty property) {
    myObject.setProperty(property);   // Here I get NullPointerException
}


// Fragment
public void onCreate() {
     // ... some code ...

     property = new ObjectProperty();
     listener.onInit(property);
}
@Override
public void onAttach(Activity activity) {
    listener = (OnInitListener) activity;  // This part is actually surrounded by try/catch, so don't worry about it
}

In summary, Fragment should initialise an object and pass it to the listener, so the Activity can set it to another object.

I'm guessing the problem is that Fragment#onCreate is being called before Activity#onCreate() and that's why I'm getting NPE but I could be wrong. Any ideas?

Christopher Francisco
  • 15,672
  • 28
  • 94
  • 206
  • maybe a duplicate? http://stackoverflow.com/questions/13941584/can-some-draw-lifecycle-of-fragment-and-its-parent-fragmentactivity – Birdy May 19 '14 at 12:06

1 Answers1

0

I don't know it for the onCreate(), but I think the fragments onCreate() will always be later the the activity's onCreate(). If I make a fragment I always use onActivityCreated(). This is called after the activity is created.

Kevin van Mierlo
  • 9,554
  • 5
  • 44
  • 76