为什么我已经创建了Activity
/ context
已经初始化了?
解释说:
我在片段的onActivityCreated
方法中,确保已创建Activity
,因此context
已初始化。我得到了以下应用程序资源:
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
...
Resources appResources = getActivity().getResources();
Log.i(TAG, "APPRESOURCES >>> " + appResources.toString());//check
ExpandableRecyclerViewAdapter expandableRecyclerView = new ExpandableRecyclerViewAdapter(getActivity(), populateList(appResources));
...
}
上面的Log.i
语句打印
APPRESOURCES >>> android.content.res.Resources@45fbef68
在上面调用的populateList(appResources)
方法中,我创建了一个MyParentObject
的对象,并将appResources
传递给它的构造函数:
private List<ParentObject> populateList(Resources appResources) {
...
MyParentObject myParentObject = new MyParentObject(appResources);
...
}
在MyParentObject
班级,
public class MyParentObject implements ParentObject {
Resources appResources;
...
public MyParentObject(Resources appResources) {
this.appResources = appResources;
}
...
private String [] spinnerFields = appResources.getStringArray(R.array.spinnerFields_arrayResource);//******ERROR********
...
}
指定spinnerFields
的声明是我获得NPE的地方。
注意:最初,我传递的是context
从getActivity()
获得的onActivityCreated()
对象。但是在调试此NPE的过程中,我改为传递appResources
对象。
答案 0 :(得分:0)
这个解决方案的功劳归功于Selvin的评论。该字段必须在构造函数之前声明,然后我在构造函数中初始化它,如下所示:
public class MyParentObject implements ParentObject {
private String [] spinnerFields;
...
public MyParentObject(Resources appResources) {
spinnerFields = appResources.getStringArray(R.array.spinnerFields_arrayResource);
}
...
}