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?