为什么有时在Activity的onCreate()之前调用Fragment的onCreate()? [英] Why Fragment's onCreate() is sometimes called prior to Activity's onCreate()?

查看:109
本文介绍了为什么有时在Activity的onCreate()之前调用Fragment的onCreate()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近,我遇到了一个难以重现的问题.当片段尝试使用Activity中的数据初始化ArrayAdapter时,将发生NPE.在Activity的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;
}

该片段还在其 onCreate()中创建一个列表适配器:

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);
}

调用默认的 getCount()方法时,NPE会出现在 AccountAdapter 中.原因是 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.

何时可能在活动的 onCreate()之前调用片段的 onCreate()?根据源代码,在活动的 onCreate()中调度Fragment的 onCreate().为什么在Activity的onCreate()完成执行后再调用它?

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?

推荐答案

在Fragments之后不调用Activity回调;片段在活动期间被调用.

The Activities callback isn't called after the Fragments; the Fragment's is called during the Activity's.

初始化 mAccounts ,然后在 Activity.onCreate()

这篇关于为什么有时在Activity的onCreate()之前调用Fragment的onCreate()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆