我有一个gridview
,应该显示图像。我已将数据库中的所有图像保存为blob。我使用hashmap
并将其添加到arraylist
。我还有每个图像的标题。我的代码如下:
ArrayList<HashMap<String, Object>> mylist = new ArrayList<HashMap<String, Object>>();
Cursor cr = dbAdapter.fetchAllMenuData();
HashMap<String, Object> map ;
cr.moveToFirst();
int k=0;
while(!cr.isAfterLast())
{
map= new HashMap<String,Object>();
map.put("Image", cr.getBlob(cr.getColumnIndex("Image")));
map.put("Title", cr.getString(cr.getColumnIndex("Title")));
k++;
mylist.add(map);
map=null;
cr.moveToNext();
}
MySimpleAdapter adapter = new MySimpleAdapter(Menu.this, mylist,
R.layout.menugrid, new String[] { "Title", "Image" },
new int[] { R.id.item_title, R.id.img });
list.setAdapter(adapter);
现在,图片的格式为byte[]
。
我正在使用ViewHolder
将特定图片和标题设置为item
中的gridview
。代码如下
holder.textView1.setText(mData.get(position).get("Title")
.toString());
// holder.textView2.setText(mData.get(position).get("Description").toString());
byte[] blob= toByteArray(mData.get(position).get("Image"));
Bitmap bt=BitmapFactory.decodeByteArray(blob,0,blob.length);
holder.imageView1.setImageBitmap(bt);
问题是hashmap
就像HashMap<String, Object>
所以我不得不写一个将Object转换为byte数组的方法。方法如下:
public byte[] toBitmap (Object obj)
{
byte[] bytes = null;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(obj);
oos.flush();
oos.close();
bos.close();
bytes = bos.toByteArray ();
return bytes;
}
catch (IOException ex) {
return null; //TODO: Handle the exception
}
此方法正确返回byte[]
。但是,我可以将其转换为位图
BitmapFactory.decodeByteArray(blob,0,blob.length);
返回null
。所以无法将其设置为imageview
。
答案 0 :(得分:2)
试试这个。这可能对你有帮助。
byte[] pic=(cursor.getBlob(position));
ByteArrayInputStream imageStream = new ByteArrayInputStream(pic);
Bitmap theImage= BitmapFactory.decodeStream(imageStream);