在向数组添加条目时,间歇性地出错。任何帮助,将不胜感激。我的代码是:
protected ArrayList<String> getSpeedDatesList(){
int idx = getCurrentIndex();
speedDatesList = null;
speedDatesList = new ArrayList<String>(width);
for(int i=0; i<width - 1; i++) {
if((speedDatesList != null) && (getSpeedDatesItem(idx) != null)) {
speedDatesList.add(getSpeedDatesItem(idx));
}
idx++;
if(idx >= (width - 1)){
idx = 0;
}
}
return speedDatesList;
}
完整的错误是:
03-09 16:26:53.864 3665-5195/uk.co.code2u.cloc_pro E/AndroidRuntime: FATAL EXCEPTION: Thread-23
Process: `uk.co.code2u.cloc_pro, PID: 3665`
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.util.ArrayList.add(java.lang.Object)' on a null object reference
at uk.co.code2u.cloc_pro.CUserStatistics.getSpeedDatesList(CUserStatistics.java:191)
at uk.co.code2u.cloc_pro.MainStatisticsActivity$MySurfaceView.run(MainStatisticsActivity.java:260)
at java.lang.Thread.run(Thread.java:762)
答案 0 :(得分:0)
更改为 -
protected ArrayList<String> getSpeedDatesList(){
int idx = getCurrentIndex();
speedDatesList = null;
speedDatesList = new ArrayList<String>();
for(int i = 0; i < width - 1; i++) {
if((speedDatesList != null) && (getSpeedDatesItem(idx) != null)) {
speedDatesList.add(getSpeedDatesItem(idx));
}
idx++;
if(idx >= (width - 1)){
idx = 0;
}
}
return speedDatesList;
}
答案 1 :(得分:0)
为什么要将数组设置为null然后创建新的ArrayList?从我所看到的,speedDatesList已经被声明并初始化了这个函数的范围。您可以调用speedDatesList.Clear()来删除列表中的所有项目,然后将新项目添加到先前声明的列表中。
我认为问题在于这行代码:
speedDatesList = null;
并删除它应该解决异常。只需确保在onCreate / onStart方法中创建一个空列表。