ArrayAdapter<String> bigSquash = new ArrayAdapter<String>(this, R.layout.adapter_xml, onPointString);
Whenever I initialize this array adapter outside the onCreate() method an error is generated, whereas when I initialize it in the onCreate() method no error is thrown. So can anybody tell me why is this happening?
LayoutInflater.from(context) will be called in the ArrayAdapter constructor If the activity does not have onCreate, it will run out of exception ,
ArrayAdapter constructor code
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 code
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 code
@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);
}
So you need to call after activity onCreate。