Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Fragment's onCreate() is sometimes called prior to Activity's onCreate()?

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?

like image 857
k_shil Avatar asked May 18 '15 08:05

k_shil


People also ask

Why onCreate is called twice?

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.

What is onCreate () meant for?

onCreate() It is called when the activity is first created.

Is onCreate called before onCreateView?

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.

Why do we need to call setContentView () in onCreate () of activity class?

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.


1 Answers

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()

like image 58
FunkTheMonk Avatar answered Nov 16 '22 00:11

FunkTheMonk