android - 使用android在sqlite数据库中插入和检索图像数据的问题

标签 android sqlite

我是安卓开发的新手。目前我在 inserting/retrieving image to SQLite database using android 时遇到问题。

//code for inserting image
InputStream in = OpenHttpConnection(imgurl);

byte[] bb = new byte[in.available()];

in.read(bb);//here the length of bb is 2040

//update query

myDataBase.execSQL("Update Product SET Image='"+bb+"' Where CatPID='"+pcpid+"'");

//function OpenHttpConnection
private InputStream OpenHttpConnection(String urlString)  throws IOException
{
    InputStream in = null;
    int response = -1;

    URL url = new URL(urlString); 
    URLConnection conn = url.openConnection();

    if (!(conn instanceof HttpURLConnection))                     
        throw new IOException("Not an HTTP connection");

    try{
        HttpURLConnection httpConn = (HttpURLConnection) conn;
        httpConn.setAllowUserInteraction(false);
        httpConn.setInstanceFollowRedirects(true);
        httpConn.setRequestMethod("GET");
        httpConn.connect(); 

        response = httpConn.getResponseCode();                 
        if (response == HttpURLConnection.HTTP_OK) {
            in = httpConn.getInputStream();                                 
        }                     
    }
    catch (Exception ex)
    {
        throw new IOException("Error connecting");            
    }
    return in;     
}

//code for retrieve image from database

byte[] bb = cursor.getBlob(cursor.getColumnIndex("Image"));//here length is only 12

ByteArrayInputStream imageStream = new ByteArrayInputStream(bb);

Bitmap theImage = BitmapFactory.decodeStream(imageStream);

img.setImageBitmap(theImage);

但是没有显示图片,日志显示“Factory returned null”

谁能帮我找出我错在哪里并提供有效解决方案的代码 fragment ?

提前致谢

最佳答案

你可以使用 decodeByteArray:

final byte[] image_byte = c.getBlob(0);
Bitmap image_bitmap = BitmapFactory.decodeByteArray(image_byte, 0, image_byte.length);

如果需要,可能还有 Bitmap.createScaledBitmap() 来重新缩放它。

关于android - 使用android在sqlite数据库中插入和检索图像数据的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4034700/

相关文章:

android - 将自定义cookie设置为ffmpeg http请求

python - 如何在 SQLITE3 上关闭和删除数据库后再次打开数据库

ruby-on-rails - 在开发过程中从 SQLite3 切换到 Postgresql 以适应 Thinking Sphinx

android - 尝试使用生成的 SDK 从 Android 进行 "Hello World"AWS API Gateway GET API 调用

android - 从支持库迁移到 AndroidX 后,某些样式属性丢失

java - 在 Android 上停止服务

php - 使用 SQLite 迁移 Laravel

java - Android Room 数据库删除查询不删除任何行

sql - 有条件地选择引用另一行的行 sqlite

android - 如何计算 SQLITE 表中的列数?