为什么在 onCreate() 方法中初始化 Array Adapter 很重要?

Why is it important to initialize Array Adapter inside the onCreate() method?

ArrayAdapter<String> bigSquash = new ArrayAdapter<String>(this, R.layout.adapter_xml, onPointString);

每当我在 onCreate() 方法之外初始化此数组适配器时,都会生成错误,而当我在 onCreate() 方法中初始化它时,不会引发任何错误。 那么有人能告诉我为什么会这样吗?

LayoutInflater.from(context) 将在 ArrayAdapter 构造函数中调用 如果 activity 没有 onCreate,它将 运行 排除异常,

ArrayAdapter 构造函数代码

private ArrayAdapter(@NonNull Context context, @LayoutRes int resource,
        @IdRes int textViewResourceId, @NonNull List<T> objects, boolean objsFromResources) {
    mContext = context;
    mInflater = LayoutInflater.from(context);
    mResource = mDropDownResource = resource;
    mObjects = objects;
    mObjectsFromResources = objsFromResources;
    mFieldId = textViewResourceId;
}

LayoutInflater.from代码

public static LayoutInflater from(Context context) {
    LayoutInflater LayoutInflater =
            (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    if (LayoutInflater == null) {
        throw new AssertionError("LayoutInflater not found.");
    }
    return LayoutInflater;
}

activity.getSystemService代码

@Override
public Object getSystemService(@ServiceName @NonNull String name) {
    if (getBaseContext() == null) {
        throw new IllegalStateException(
                "System services not available to Activities before onCreate()");
    }

    if (WINDOW_SERVICE.equals(name)) {
        return mWindowManager;
    } else if (SEARCH_SERVICE.equals(name)) {
        ensureSearchManager();
        return mSearchManager;
    }
    return super.getSystemService(name);
}

所以需要在activityonCreate之后调用。

这与Activity父classContextWrapper

的变量mBase的初始化有关

Activity 开始进程

ActivityThread.performLaunchActivity -> Activity.attach -> Activity.attachBaseContext -> ContextThemeWrapper.attachBaseContext -> ContextWrapper.attachBaseContext -> ContextWrapper.mBase init

Activity的onCreate()方法会在attach()

之后调用

如果在mBase初始化之前调用Activity的getSystemService(),会因为mBase变量为空而出现异常

new ArrayAdapter(activity) -> LayoutInflater.from(context) -> Activity.getSystemService -> Activity.getBaseContext is null throw IllegalStateException

如果您需要更详细的信息,请查看Activity

的启动过程