gpt4 book ai didi

java - 尝试从从 sqlite 中提取的对象列表中调用方法时的空对象引用

转载 作者:行者123 更新时间:2023-11-30 01:46:29 24 4
gpt4 key购买 nike

从 sqlite 数据库中提取一些数据并将其传递给另一个类后,我无法诊断错误。我认为传递是我遇到问题的地方。

事实:我的数据库中充满了以下格式的数据:

1447206226445|1
1447206228288|0
1447206462437|1

(第一列是长整数,第二列是整数)

在我的主类中,我试图在数据库中搜索一系列长值,并相应地显示内容。我使用:

Days[] daysList = dbHandler.findRange(first.getTimeInMillis(), last.getTimeInMillis());

获取我想要的日期列表,其中 firstlast 是 Calendar 对象。

然后我使用:

for (int i = 0; i < 7; i++) {
for (int j = 0; j < daysList.length; j++) {
if (daysList[j].getID() > first.getTimeInMillis() && daysList[j].getID() < second.getTimeInMillis()) {
...
...
...

对daysList中的数据进行排序。但是,我在这里收到以下错误:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'long com.example.william.timeclockr.Days.getID()' on a null object reference

这是我的 DBHandler findRange() 方法:

public Days[] findRange(long startRange, long endRange) {
String query = "Select * FROM " + TABLE_DAYS + " WHERE " + COLUMN_DAYSLONG + " >= " + startRange + " AND " + COLUMN_DAYSLONG + " <= " + endRange + ";";

SQLiteDatabase db = this.getWritableDatabase();

Cursor cursor = db.rawQuery(query, null);

Days day = new Days();
Days[] days = new Days[cursor.getCount()];
int i = 0;
cursor.moveToFirst();

do {
//while (cursor.moveToNext()) {
day.setID(cursor.getLong(0));
day.setStatus(cursor.getInt(1));
days[i] = day;
i++;
cursor.moveToNext();
//}
} while (cursor.moveToNext());

cursor.close();
db.close();
return days;
}

这是我的 Days 类(class):

package com.example.william.timeclockr;

public class Days {

private long _id;
private int _status;

public Days() {

}

public Days(long id, int status) {
this._id = id;
this._status = status;
}

public Days(int status) {
this._status = status;
}

public void setID(long id) {
this._id = id;
}

public long getID() {
return this._id;
}

public void setStatus(int status) {
this._status = status;
}

public int getStatus() {
return this._status;
}
}

我知道这是很多信息,但我觉得我在传递该列表时犯了一个非常菜鸟的错误,有什么帮助吗?

最佳答案

问题似乎都在您的 do-while 中在 findRange() 中循环方法。您需要实例化一个新的 Days对象每次通过循环。此外,您正在调用 cursor.moveToNext();每次通过两次,这是在推进Cursor比数组索引更快,导致最终的 NullPointerException .

do {
day = new Days();
day.setID(cursor.getLong(0));
day.setStatus(cursor.getInt(1));
days[i] = day;
i++;
} while (cursor.moveToNext());

关于java - 尝试从从 sqlite 中提取的对象列表中调用方法时的空对象引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33643553/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com