【问题标题】:getting images from database android从数据库android获取图像
【发布时间】:2011-12-06 07:20:07
【问题描述】:

我有一个gridview,应该在其中显示图像。我已将数据库中的所有图像保存为 blob。我正在使用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 将特定图像和标题设置为gridview 中的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&lt;String, Object&gt; 所以我必须编写一个将对象转换为字节数组的方法。方法如下:

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

【问题讨论】:

    标签: android sqlite bytearray android-view android-gridview


    【解决方案1】:

    试试这个。这可能会帮助你。

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

    【讨论】:

    猜你喜欢
    • 2016-06-25
    • 2014-05-24
    • 2021-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多