Java 使用嵌套类引用成员变量对象时出现空对象引用错误
我在Java 使用嵌套类引用成员变量对象时出现空对象引用错误,java,android,object,nested,Java,Android,Object,Nested,我在ShareActivity的onCreate()方法中实例化一个“MwVolley”对象,在那里引用它,然后在ShareActivity的嵌套类中再次引用该对象 因此,我将此对象声明为ShareActivity的成员变量: protected MwVolley apiCall; 然后通过调用onCreate()中的构造函数来实例化它,并多次引用它: apiCall = new MwVolley(this); Log.d("Repeat", "Logging apiCall
ShareActivity
的onCreate()
方法中实例化一个“MwVolley”对象,在那里引用它,然后在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>();
}
}
}
如果我注释掉apiCall.getRadius()并给它一个任意的int,它将继续执行该操作,但在下一次apiCall
引用时再次导致空对象引用错误
我做错什么了吗?我认为所有嵌套类都可以自由访问其封闭类的成员变量,即使是私有和受保护的成员变量。我知道当我在onCreate()
中调用构造函数时,对象被实例化了,因为我可以在那里记录和引用对象
不幸的是,我无法将整个ShareActivity
类的代码粘贴到这里(太长),但如果需要,它可以全部打开
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)