Question

I have a gridview where images should be displayed. I have saved all the images in databases as blobs. Iam using a hashmap and adding it to arraylist. I also have a title along with each image. My code is as follows:

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);

Now, Image is in the form of byte[].

I am using a ViewHolderto set the particular image and title to an item in the gridview. the code is as follows

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);  

The problem is the hashmap is like HashMap<String, Object> so i had to a write a method that converts Object to byte array. The method is as follows:

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
      }

This method is returning byte[] correctly. But, i could convert it into a bitmap BitmapFactory.decodeByteArray(blob,0,blob.length); returns null. so could not set it to imageview.

Was it helpful?

Solution

Try this. This might help you.

 byte[] pic=(cursor.getBlob(position));   
  ByteArrayInputStream imageStream = new ByteArrayInputStream(pic);
  Bitmap theImage= BitmapFactory.decodeStream(imageStream);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top