2016-12-01 9 views
0

通常、このコードは非常にうまく機能します。しかし、 "cursor"が空の場合、main.classにエラーがあります。私はたくさんのことを試しました。しかし、私は成功しませんでした。方法を解決するためにお手伝いください。Sqliteの空のカーソルエラー?

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

障害カーソルがデータを含まない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()); 
    } 
+0

_Iは何をすべきかを、ヌル/空/ゼロ.. cursor_を使用する必要がありますか?それらのどれも読むことはできません。 – AxelH

+0

'while(cursor.moveToNext()){...}' – pskink

+0

エラーは何ですか? – laalto

答えて

1

場合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()); 
    } 

障害、moveToFirst()戻る偽。だからあなたの最初のスニペットであなたのif (cursor.moveToFirst())条件のelse枝に扱う特別な空のカーソルを追加します。

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 
} 
+0

申し訳ありませんが、もう一度解決しませんでした。私のコードの例を私に見せてください。 –

+0

私は自分の質問を更新しました。もう一度見てください。 –

関連する問題