English 中文(简体)
Android:从数据库检索位图出现问题
原标题:Android: problem retrieving bitmap from database

当我从sqlite数据库检索图像时,我的Bitmap对象bm返回null值,有人可以帮我吗..?

我在我的数据库中找到了问题。

当我将字节数组存储在数据库表中的blob数据类型中时,字节数组的大小为2280。

但是当我使用选择查询检索该blob数据类型时,我得到大小为12的字节数组。

我的代码是:

// Inserting data in database
byte[] b;  
ByteArrayOutputStream baos = new ByteArrayOutputStream();  
Bitmap bm = BitmapFactory.decodeResource(getResources(),R.drawable.icon);  
bm.compress(Bitmap.CompressFormat.PNG, 100, baos); //bm is the bitmap object  
b = baos.toByteArray();  
//here b size is 2280  
baos.close();  
try  
{  
mDB = this.openOrCreateDatabase(MY_DATABASE_NAME, MODE_PRIVATE, null);  
mDB.execSQL("CREATE TABLE IF NOT EXISTS "
+ MY_DATABASE_TABLE
+ " (PICTURE BLOB);");    
mDB.execSQL("INSERT INTO "
+ MY_DATABASE_TABLE
+ " (PICTURE)"
+ " VALUES ( "+b+" );");  

}  
catch(Exception e)  
{  
Log.e("Error", "Error", e);  
}  

finally  
{  
if(mDB != null)  
mDB.close();  
}  


// Retriving data from database  
byte[] b1;  
Bitmap bm;  
mDB = this.openOrCreateDatabase(MY_DATABASE_NAME, MODE_PRIVATE, null);  
try {  
mDB.execSQL("CREATE TABLE IF NOT EXISTS "
+ MY_DATABASE_TABLE
+ " (PICTURE BLOB);");  

Cursor c = mDB.rawQuery("SELECT * FROM " + MY_DATABASE_TABLE + ";", null);  
c.moveToFirst();  
if (c != null) {  
do {  
b1=c.getBlob(0)); //here b1 size is 12   
bm=BitmapFactory.decodeByteArray(b1, 0, b1.length);   
}while(c.moveToNext());  
}  
问题回答

这是我将图像编码后写入数据库的方法:

ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
mBitmap.compress(Bitmap.CompressFormat.JPEG, THUMB_QUALITY, outputStream);
mByteArray = outputStream.toByteArray();  // write this to database as blob

然后将其解码,格式类似于光标: Ránhòu jiāng qí jiěmǎ, géshì lèisì yú guāngb标:

ByteArrayInputStream inputStream = new ByteArrayInputStream(cursor.getBlob(columnIndex));
Bitmap mBitmap = BitmapFactory.decodeStream(inputStream);




相关问题
Instead of NULL, should I write `0x0` or `0`?

I know that you are supposed to use 0 instead of NULL in c++ (even though NULL is defined as 0 in C++ most of the time). Recently I came across some code where 0x0 was used instead, though. What is ...

SELECT the newest record with a non null value in one column

I have table data which looks like this id | keyword | count | date 1 | ipod | 200 | 2009-08-02 2 | ipod | 250 | 2009-09-01 3 | ipod | 150 | 2009-09-04 4 | ipod | NULL | 2009-09-07 Now what I am ...

C#: Range intersection when endpoints are null (infinity)

Ok, I have these intersection methods to work with ranges, and they work well as long as the range endpoints are not null: public static bool Intersects<T>(this Range<T> first, Range<T&...

How can I store NULLs in NOT NULL field?

I just came across NULL values in NOT-NULL fields in our test database. How could they get there? I know that NOT-NULL constraints can be altered with NOVALIDATE clause, but that would change table s ...

热门标签