Android 如何显示数据库中的图像

Android 如何显示数据库中的图像,android,database,Android,Database,我想显示存储在数据库中的图像,但是我的程序抛出了一个异常(CursorIndexOutOfBoundsException:请求索引-1,大小为100)。 我正在使用,在本教程中,我成功地将图像插入到数据库中,但检索它们是个问题。 为了从google和StackOverflow中找到答案,我还遇到了以下问题。 .然而,这些问题对我的情况没有帮助。任何帮助都将不胜感激 下面是我的代码 db = helper.getWritableDatabase(); //select

我想显示存储在数据库中的图像,但是我的程序抛出了一个异常(CursorIndexOutOfBoundsException:请求索引-1,大小为100)。 我正在使用,在本教程中,我成功地将图像插入到数据库中,但检索它们是个问题。 为了从google和StackOverflow中找到答案,我还遇到了以下问题。 .然而,这些问题对我的情况没有帮助。任何帮助都将不胜感激

下面是我的代码

    db = helper.getWritableDatabase();      
    //select the data
    //while(cursor.moveToFirst());
     cursor = db.query(DBHelper.TABLE, new String[] {DBHelper.C_PHOTOS },
                 null, null, null, null, null);

    //get it as a ByteArray
    byte[] imageByteArray=cursor.getBlob(1);
    //the cursor is not needed anymore
    cursor.close();
     
    //convert it back to an image
    ByteArrayInputStream imageStream = new ByteArrayInputStream(imageByteArray);
    Bitmap theImage = BitmapFactory.decodeStream(imageStream);
这是插入图像的clase

       URL url = new URL("myurl");
             URLConnection ucon = url.openConnection();
             InputStream is = ucon.getInputStream();
             BufferedInputStream bis = new BufferedInputStream(is,128);
             ByteArrayBuffer baf = new ByteArrayBuffer(128);
             int current = 0;
             while ((current = bis.read()) != -1) {
                     baf.append((byte) current);
             }
            ContentValues v = new ContentValues();          
            v.put(DBHelper.C_PHOTOS,baf.toByteArray());
            v.put(DBHelper.C_PHOTOS, photoThumbnailUrl);
            db.insert(DBHelper.TABLE, null, v);
提前感谢

试试这个:

byte[] imageByteArray = cursor.getBlob(cursor.getColumnIndex(DBHelper.C_PHOTOS));

在从光标获取任何信息之前,我非常确定您必须使用
moveToFirst()
设置光标的位置。这可以解释为什么它认为它的指数是-1。光标尚未设置为查询行列表的开头


Brian Dupuis的回答还描述了一种更好(更安全)的获取行-列的方法,通过
getColumnIndex()

在数据库中只存储图像路径可能更好。然后将图像存储在您的“图像”文件夹中。您好,这些图像来自web,而不是任何文件夹。@Brain,感谢您的回复,但是这并没有停止异常,我当前收到了此消息(02-06 23:09:50.057:E/AndroidRuntime(2384):java.lang.RuntimeException:无法启动活动组件信息{com.guid/com.guid.image}:android.database.CursorIndexOutOfBoundsException:已从LogCat请求索引-1,大小为220)。请稍候。。。您注释掉了
光标。movetoFirst()
。尝试将一个放在
getBlob()
@Brain之前,感谢您敏锐的眼光和专业知识,将光标移动到第一个位置可以阻止异常。如果有人能帮助我解决此问题,我将不胜感激,尝试将图像显示为listview im接收到以下内容:resolveUri失败,错误的位图uri显示了数据库中的所有图像。