引用具有嵌套类的成员变量对象时出现空对象引用错误

时间:2016-01-04 02:32:28

标签: java android object nested

我实例化了一个" MwVolley" onCreate() ShareActivity方法中的对象,在那里引用它,然后再在ShareActivity的嵌套类中再次引用该对象。

所以我将此对象声明为ShareActivity

的成员变量
protected MwVolley apiCall;

然后通过调用onCreate()中的构造函数来实例化它,并引用它几次:

    apiCall = new MwVolley(this);
    Log.d("Repeat", "Logging apiCall object in onCreate: " + apiCall.toString());

    if (filePath != null) {
        //extract the coordinates of image in decimal degrees
        Log.d("Image", "Calling GPSExtractor");
        GPSExtractor imageObj = new GPSExtractor(filePath);
        String coords = imageObj.getCoords();

        if (coords != null) {
            Log.d("Image", "Coords of image: " + coords);

            apiCall.setCoords(coords);
            //asynchronous calls to MediaWiki Commons API to match image coords with nearby Commons categories
            apiCall.request();

然后稍后尝试在嵌套类ResponseListener中再次引用它:

protected class ResponseListener<T> implements Response.Listener<T> {

    private final String TAG = ResponseListener.class.getName();

    @Override
    public void onResponse(T response) {

        int currentRadius = apiCall.getRadius();
        int nextRadius = currentRadius * 10;

        Log.d(TAG, response.toString());
        Log.d("Repeat", "Logging apiCall object in ResponseListener: " + apiCall.toString());
        Log.d("Repeat", "categorySet contains: " + apiCall.categorySet.toString());

        if (nextRadius <= 10000 && apiCall.categorySet.size() <= 10) {

            apiCall.setRadius(nextRadius);
            Log.d("Repeat", "Repeating API call with radius " + Integer.toString(nextRadius));

            apiCall.request();

        }

        if (apiCall.getGpsCatExists() == true) {
            gpsItems = new ArrayList<String>(apiCall.getGpsCat());
            Log.d("Cat", "GPS items: " + gpsItems.toString());

        } else {
            gpsItems = new ArrayList<String>();
        }
    }
}

这会导致错误:

01-04 02:28:08.450: E/ACRA(4430): fr.free.nrw.commons fatal error : Attempt to invoke virtual method 'int fr.free.nrw.commons.upload.MwVolley.getRadius()' on a null object reference
01-04 02:28:08.450: E/ACRA(4430): java.lang.NullPointerException: Attempt to invoke virtual method 'int fr.free.nrw.commons.upload.MwVolley.getRadius()' on a null object reference
01-04 02:28:08.450: E/ACRA(4430):   at fr.free.nrw.commons.upload.ShareActivity$ResponseListener.onResponse(ShareActivity.java:227)

如果我注释掉apiCall.getRadius()并给它一个任意的int,它会在那里继续,但是在下一个apiCall引用时会再次导致空对象引用错误。

我在这里做错了吗?我认为所有嵌套类都可以自由访问其封闭类的成员变量,甚至是私有和受保护的类。我知道当我在onCreate()中调用构造函数时,对象已被实例化,因为我可以在那里记录并引用该对象。

很遗憾,我无法在此处粘贴整个ShareActivity课程的代码(太长时间),但如果需要,它会全部放在https://github.com/misaochan/apps-android-commons/tree/repeat-calls上。

0 个答案:

没有答案