2011-12-06 77 views
0

我有一個gridview應該顯示圖像。我已將所有圖像保存在數據庫中作爲斑點。 Iam使用hashmap並將其添加到arraylist。我也有一個標題,每個圖像。我的代碼如下:從數據庫中獲取圖像android

現在
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[]形式。

我正在使用ViewHoldergridview中的特定圖像和標題設置爲item。的代碼如下

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

回答

2

試試這個。這可能會幫助你。

byte[] pic=(cursor.getBlob(position)); 
    ByteArrayInputStream imageStream = new ByteArrayInputStream(pic); 
    Bitmap theImage= BitmapFactory.decodeStream(imageStream); 
+0

:你好,如果你想幫助我呢? http://stackoverflow.com/questions/15954896/how-to-save-image-taken-from-camera-and-show-it-to-listview-crashes-with-ille.Thanks – George