Sqlite空游标错误?

时间:2016-12-01 14:37:51

标签: android sqlite

Normaly,这段代码运作得很好。但是,如果"光标"为空,main.class中有错误。我尝试了很多东西。但是,我没有取得成功。请帮忙解决问题。

---- database.class ----

  public List<Integer> count_a() {
    List<Integer> list = new ArrayList<Integer>();

    String selectQuery = "select book, count(date) from myTAB WHERE (date>'" + 0 + "') group by book"; 
// if result is empty, there is an error in main.class.
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);

    if (cursor.moveToFirst()) {
        do {
            list.add(Integer.parseInt(cursor.getString(1)));
        }
        while (cursor.moveToNext());
    }

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

---- main.class ----

 private void load_data() {
    Database db = new Database(getApplicationContext());

    List<Integer> co_a = db.count_a(); // error is here

    Integer[] co_b = new Integer[co_a.size()];
    co_b = co_a.toArray(co_b);

    List_Row adapter = new List_Row(this, co_b);
    ListView lv = (ListView) findViewById(R.id.lvStat);
    lv.setAdapter(adapter);
}

失败1

    if (cursor.moveToFirst()) {
        do {
            if (cursor.getCount() == 0 || cursor == null) {
                list.add(0);
            } else {
                list.add(Integer.parseInt(cursor.getString(1)));
            }
        }
        while (cursor.moveToNext());
    }

失败2

  if (cursor.moveToFirst()) {
        do {
            if(cursor.getCount() == 0){
                list.add(0);
            }else {
                list.add(Integer.parseInt(cursor.getString(1)));
            }
        }
        while (cursor.moveToNext());
    }

失败3

    if (cursor != null && cursor.moveToFirst()) {
        do {
            if (cursor.getCount() > 0) {
                list.add(Integer.parseInt(cursor.getString(1)));
            } else {
                list.add(0);
            }
        }
        while (cursor.moveToNext());
    }

失败4

    if (cursor.moveToFirst()) {
        do {
            if (cursor != null && cursor.getCount() > 0) {
                list.add(Integer.parseInt(cursor.getString(1)));
            } else {
                list.add(0);
            }
        }
        while (cursor.moveToNext());
    }

失败5

if (cursor.moveToFirst()) {
        do {
            list.add(Integer.parseInt(cursor.getString(1)));
        }
        while (cursor.moveToNext());
    }
    if (cursor.isBeforeFirst()){
        do {
            list.add(0);
        }
        while (cursor.moveToNext());
    }

1 个答案:

答案 0 :(得分:1)

如果游标不包含任何数据,moveToFirst()将返回false。因此,在您的第一个代码段中,将任何特殊的空光标处理添加到else条件的if (cursor.moveToFirst())分支:

if (cursor.moveToFirst()) {
    do {
        list.add(Integer.parseInt(cursor.getString(1)));
    }
    while (cursor.moveToNext());
} else {
    // whatever you'd like to do in case of no data
}