尝试从sqlite

时间:2015-11-11 02:59:24

标签: java android sqlite android-studio android-sqlite

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

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

1447206226445|1
1447206228288|0
1447206462437|1

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

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

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

获取我想要的日期列表,其中 first last 是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课程:

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;
    }
}

我知道这是一个很多信息,但是我觉得我正在犯这样一个错误的错误传递这个列表,有什么帮助吗?

1 个答案:

答案 0 :(得分:1)

问题似乎出现在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());