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?