Recently I came across a hard to reproduce issue. The NPE occurs when a fragment tries to initialize ArrayAdapter with the data from Activity. The default list initialized in Activity's onCreate method:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// ...
mAccounts = new ArrayList<>();
// ...
}
@Override
public List<Account> getAccounts(){
return mAccounts;
}
The fragment creates a list adapter also in its onCreate():
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
setHasOptionsMenu(true);
//mAccountProvider is an interface implemented by the activity
mAccounts = mAccountProvider.getAccounts();
mAccountAdapter = new AccountAdapter(getActivity(), R.layout.account_list_item, mAccounts);
}
The NPE occurs inside the AccountAdapter when default getCount() method is called. The reason is that mAccounts is null. The issue appears seldom and I wasn't able to reproduce it.
When is it possible that fragment's onCreate() is called before activity's onCreate()? According to the source code, Fragment's onCreate() is dispatched in the Activity's onCreate(). Why is is it then called after Activity's onCreate() has finished its execution?
onCreate will get called when your activity has been destroyed and recreated, which happens any time the device is rotated, the keyboard is opened, or you switch apps and the system decides it's time to reclaim some memory and kill off your app.
onCreate() It is called when the activity is first created.
onCreate() is called to do initial creation of the fragment. onCreateView() is called by Android once the Fragment should inflate a view. onViewCreated() is called after onCreateView() and ensures that the fragment's root view is non-null . Any view setup should happen here.
As onCreate() of an Activity is called only once, this is the point where most initialization should go: calling setContentView(int) to inflate the activity's UI, using findViewById to programmatically interact with widgets in the UI, calling managedQuery(android.
The Activities callback isn't called after the Fragments; the Fragment's is called during the Activity's.
Initialise mAccounts
before calling super.onCreate()
in Activity.onCreate()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With