为什么我在`getResources()。getStringArray()`中获取NullPointerException,而Activity已经创建了?

时间:2015-07-24 15:40:46

标签: android android-fragments nullpointerexception android-resources android-context

为什么我已经创建了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的地方。

注意:最初,我传递的是contextgetActivity()获得的onActivityCreated()对象。但是在调试此NPE的过程中,我改为传递appResources对象。

1 个答案:

答案 0 :(得分:0)

这个解决方案的功劳归功于Selvin的评论。该字段必须在构造函数之前声明,然后我在构造函数中初始化它,如下所示:

public class MyParentObject implements ParentObject {   
        private String [] spinnerFields;     
        ...
        public MyParentObject(Resources appResources) {         
            spinnerFields = appResources.getStringArray(R.array.spinnerFields_arrayResource);   
        }
        ...     
}