我有一个gridview
应该显示图像的位置。我已将数据库中的所有图像保存为 blob。我正在使用 ahashmap
并将其添加到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[]
.
我正在使用 aViewHolder
将特定图像和标题设置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 转换为字节数组的方法。方法如下:
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
.