简体   繁体   English

从 SQLite 数据库中检索图像(BLOB 数据类型)

[英]Retrieving image from SQLite Database (BLOB data type)

I have tried to retrieve the byte[] from my SQLite DB using the code:我尝试使用以下代码从我的 SQLite DB 中检索 byte[]:

public byte[] getImageData() throws SQLException{
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery("SELECT AVATAR_IMAGE FROM AVATAR_TABLE WHERE AVATAR_ID = 1", null);
    cursor.moveToFirst();


    byte[] blob = cursor.getBlob(1);
    return blob;
}

Error returned:返回错误:

 java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { dat=content://com.android.providers.media.documents/document/image:241292 flg=0x1 }} to activity {com.example.physicalactivity/com.example.physicalactivity.ProfileActivity}: android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 1

Your query:您的查询:

SELECT AVATAR_IMAGE FROM AVATAR_TABLE WHERE AVATAR_ID = 1

returns only 1 column and since the column indices in a cursor are 0 based, you should retrieve it with:仅返回 1 列,并且由于 cursor 中的列索引基于0 ,因此您应该使用以下命令检索它:

byte[] blob = cursor.getBlob(0);

Also, you should use moveToFirst() to check if the cursor returned any rows before retrieving the column's value:此外,您应该使用moveToFirst()检查 cursor 在检索列值之前是否返回任何行:

byte[] blob = null;
if (cursor.moveToFirst()) blob = cursor.getBlob(0);
return blob;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM