รับค่าฟิลด์ด้วยเคอร์เซอร์

ฉันกำลังสร้างแอปพลิเคชันและฉันมีปัญหากับ Cursor ฉันมี SQLiteDatabase ที่ส่งคืน Cursor ให้ฉันเมื่อฉันพยายามดึงค่าด้วยฟังก์ชันนี้:

public Cursor fetchOption(long rowId) throws SQLException {

    Cursor mCursor = mDb.query(true, DATABASE_TABLE, new String[] {KEY_ROWID,
        KEY_TITLE, KEY_BODY}, KEY_ROWID + "=" + rowId, null,
        null, null, null, null);
    if (mCursor != null) {
        mCursor.moveToFirst();
    }
    return mCursor;

}

ฉันไม่รู้วิธีรับค่าของฟิลด์ใน Cursor ถ้าฉันทำเช่นนั้น:

String a = mOptionDb.fetchOption(0).getColumnName(0).toString();
String b = mOptionDb.fetchOption(0).getColumnName(1).toString();
String c = mOptionDb.fetchOption(0).getColumnName(2).toString();

ฉันได้รับเฉพาะชื่อของคอลัมน์ (_id, title, body) แต่ไม่ใช่ค่า มีข้อเสนอแนะเกี่ยวกับวิธีการบรรลุเป้าหมายนี้หรือไม่?


person Michaël    schedule 24.05.2009    source แหล่งที่มา


คำตอบ (3)


ฉันคิดว่าคุณสามารถลืมการตรวจสอบค่าว่างได้

ตรวจสอบว่ามีข้อมูลหรือไม่ จากนั้นจึงเข้าถึงคอลัมน์โดยใช้เคอร์เซอร์:

Cursor cursor = fetchOption(0);

if (cursor.moveToFirst()) // data?
   System.out.println(cursor.getString(cursor.getColumnIndex("title")); 

cursor.close(); // that's important too, otherwise you're gonna leak cursors

การอ่านบทช่วยสอน Android ก็อาจเหมาะสมเช่นกัน ดูเหมือนว่าบทช่วยสอนแผ่นจดบันทึกจะพอดีกับใบเสร็จ: http://developer.android.com/guide/tutorials/notepad/index.html

person Mariano Kamp    schedule 24.05.2009
comment
ขอขอบคุณสำหรับความช่วยเหลือของคุณ. ตอนนี้มันใช้งานได้ ลืมทุกการเข้าถึงเพื่อปิดเคอร์เซอร์... - person Michaël; 25.05.2009
comment
ทุกครั้งที่เกิดปัญหานี้ ฉันกลับมาที่นี่อีกครั้งและพบว่าลืม cursor.moveToFirst() ขอบคุณ! - person user1549672; 03.08.2013

คุณสามารถใช้เมธอด Cursor's get* เพื่อดึงค่าจากผลลัพธ์:

long id = cursor.getLong(cursor.getColumnIndex("_id"));
long title = cursor.getString(cursor.getColumnIndex("title"));
...

แนวทางปฏิบัติที่ดีกว่าคือการใช้ค่าคงที่ (มักจัดทำโดย ContentProviders) แทนที่จะเรียกไปที่ getColumnIndex ด้วยสตริงฮาร์ดโค้ด

person Josef Pfleger    schedule 24.05.2009
comment
โดยมีส่วน : int a = mOptionDb.fetchOption(0).getColumnIndex(title); ฉันได้รับ 1. แต่ด้วย mOptionDb.fetchOption(0).getString(a); ฉันได้รับข้อผิดพลาด: ERROR/AndroidRuntime(628): Uncaught handler: thread main exiting Due to uncaughtException ERROR/AndroidRuntime(628): android.database.CursorIndexOutOfBoundsException: Index 0ร้องขอ ด้วยขนาด 0 มันเหมือนกับไม่มีข้อมูล ?! - person Michaël; 24.05.2009

คุณสามารถใช้กลไกนี้ได้

Cursor record=db.test(finalDate);     
if(record.getCount()!=0){
    if(record.moveToFirst()){
        do{               
            Imgid1=record.getString(record.getColumnIndex(Database.PHOTO));                
        }while(record.moveToNext());                          
    } 
    record.close();        
}
person Community    schedule 26.09.2012