这是我的代码的第一个版本:
public class ListSchedule implements ListInterface {
private ArrayList<Schedule> list;
private String cookie;
public ListSchedule() {
this.list = new ArrayList<Schedule>();
}
public ArrayList<Schedule> getList() {
return list;
}
}
在另一个类上,我打了这个电话:
protected final ListSchedule parse(String jsonString)
throws CustomException {
ListSchedule list = new ListSchedule();
JSONArray schedulesArray;
try {
// Convert the response to a JSONObject
JSONObject json = new JSONObject(jsonString);
try {
int errorCode = json.getInt("error");
// Check if there is no error from FilBleu server
if (errorCode > 0) {
throw new CustomException(
CustomException.ERROR_FILBLEU,
"DataAccessObject", "Server error "
+ json.getInt("subError"));
}
try {
String cookie = json.getString("cookie");
list = new ListSchedule(cookie);
} catch (JSONException e) {
throw new CustomException(CustomException.JSON_FORMAT,
"DataAccessObject", "No cookie value");
}
schedulesArray = json.getJSONArray("schedules");
// NullPointerException with the line below
Log.d("DAO", list.getList().toString());
parseSchedulesArray(list, schedulesArray);
} catch (JSONException e) { // Unable to get the error code
throw new CustomException(CustomException.JSON_FORMAT,
"DataAccessObject", "Bad JSON format ("
+ e.getMessage() + ")");
}
} catch (JSONException e) { // Unable to convert response
throw new CustomException(CustomException.JSON_FORMAT,
"DataAccessObject", "Bad JSON format ("
+ e.getMessage() + ")");
}
return list;
}
然后我在 Log.d("DAO", list.getList().toString());
行中遇到了 NullPointerException
。所以我尝试了另一种解决方案。正如您所看到的,唯一的区别是 list
属性的初始化:
public class ListSchedule implements ListInterface {
private ArrayList<Schedule> list = new ArrayList<Schedule>();
private String cookie;
public ListSchedule() {
}
public ArrayList<Schedule> getList() {
return list;
}
}
并且 NullPointerException
再也没有抛出......
我不太明白初始化 list
属性的两种方法之间的区别。有人可以给我提示吗?
最佳答案
我推测您的代码库中存在以下构造函数:
public ListSchedule(String cookie) {
this.cookie = cookie;
}
您需要的是以下内容:
public ListSchedule(String cookie) {
this.cookie = cookie;
this.list = new ArrayList<Schedule>();
}
通过在程序中调用此行可以进一步验证这一点:
list = new ListSchedule(cookie);
请注意,您没有在第二个构造函数中初始化列表。此外,您首先调用默认构造函数,但稍后将指向该对象的指针重新分配给从 ListSchedule 的 String 构造函数创建的内容。
关于java - Java 构造函数中的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11365313/