画像を表示するgridview
場所があります。データベース内のすべての画像をブロブとして保存しました。を使用して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>
をバイト配列に変換するメソッドを作成する必要があったことです。方法は次のとおりです。
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
。