![](/img/trans.png)
[英]Are there other ways to fetch data from the SQLite database except using Cursor?
[英]How to fetch data from multiple columns in sqlite android using cursor
我想使用以下代碼使用光標從多行和多列中獲取數據
Cursor getallrecords(){
SQLiteDatabase dbb = this.getReadableDatabase();
Cursor cursor = null;
if (dbb != null){
Log.d("cursor","not null");
cursor = dbb.rawQuery(" SELECT * FROM " + TABLE_NAME,null);
}else{
Log.d("cursor","null");
}
return cursor;
}
在 logcat 上它顯示 cursor 不為空並返回數據。 但是當我嘗試使用下面的代碼設置 cursor 進行 ArrayList 的數據時。
void read(){
Cursor cursor = save_barcode.getallrecords();
if (cursor.getCount() != 0){
cursor.moveToFirst();
while(cursor.moveToNext()){
url.add(cursor.getString(1));
type.add(cursor.getString(2));
date_and_time.add(cursor.getString(3));
}
}
if (!url.isEmpty()){
Log.d("message","not null");
}else {
Log.d("url","null");
}
if (!type.isEmpty()){
Log.d("message","not null");
}else {
Log.d("type","null");
}
if (!date_and_time.isEmpty()){
Log.d("message","not null");
}else {
Log.d("date","null");
}
}
然后在logcat中顯示URL,date_and_time,type這三個都是空的。 因此,如果有人知道如何使用 cursor 從多行和多列中獲取數據,請幫助我
您的代碼的明顯問題是您使用的是moveToFirst()
,然后是moveToNext()
,因此可以肯定的是您丟失了第一行。
如果表格中只有 1 行,則列表將為空。
無需檢查getCount()
,因此刪除if
且不需要moveToFirst()
。
更改為:
void read(){
Cursor cursor = save_barcode.getallrecords();
if (cursor == null) return;
while (cursor.moveToNext()) {
url.add(cursor.getString(1));
type.add(cursor.getString(2));
date_and_time.add(cursor.getString(3));
}
cursor.close();
...................
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.