title: getting images from database android
body: <p>I have a <code>gridview</code> where images should be displayed. I have saved all the images in databases as blobs. Iam using a <code>hashmap</code> and adding it to <code>arraylist</code>. I also have a title along with each image. My code is as follows:  </p>
  
  <pre><code>ArrayList&lt;HashMap&lt;String, Object&gt;&gt; mylist = new ArrayList&lt;HashMap&lt;String, Object&gt;&gt;();
          Cursor cr = dbAdapter.fetchAllMenuData();
  
  
              HashMap&lt;String, Object&gt; map ;
  
  
               cr.moveToFirst();
  
                  int k=0;
                  while(!cr.isAfterLast())
                  {
                   map= new HashMap&lt;String,Object&gt;();
                   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);
  </code></pre>
  
  <p>Now, Image is in the form of <code>byte[]</code>. </p>
  
  <p>I am using a <code>ViewHolder</code>to set the particular image and title to an <code>item</code> in the <code>gridview</code>. the code is as follows  </p>
  
  <pre><code>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);  
  </code></pre>
  
  <p>The problem is the <code>hashmap</code> is like <code>HashMap&lt;String, Object&gt;</code> so i had to a write a method that converts Object to byte array. The method is as follows:</p>
  
  <pre><code>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
        }
  </code></pre>
  
  <p>This method is returning <code>byte[]</code> correctly. But, i could convert it into a bitmap
  <code>BitmapFactory.decodeByteArray(blob,0,blob.length);</code> returns <code>null</code>. so could not set it to <code>imageview</code>.</p>