这是我的代码的第一个版本:参考Java中构造
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
属性。有人可以给我一个提示吗?
,如果你无法理解的差异,你应该阅读一个基本的程序手册 – Blackbelt 2012-07-06 15:39:28
@blackbelt:我实际上不理解带有NullPointerException的行为。 – mithrop 2012-07-06 15:41:42
@blackbelt:不是。他的代码显然是正确的。事实上,我之前看到过这种奇怪的行为,找不到一个好的解释。他显然调用构造函数,并且列表应该被初始化,但事实并非如此。 – Tudor 2012-07-06 15:41:52