come ottenere le immagini dal database android
-
28-10-2019 - |
Domanda
Ho un gridview
dove le immagini devono essere visualizzate.Ho salvato tutte le immagini in un database blob.Iam utilizzando un hashmap
e l'aggiunta di arraylist
.Ho anche avere un titolo lungo con ogni immagine.Il mio codice è il seguente:
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);
Ora, l'Immagine è in forma di byte[]
.
Io sto usando una ViewHolder
per impostare l'immagine e il titolo di un item
nel gridview
.il codice è il seguente
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);
Il problema è il hashmap
è come HashMap<String, Object>
ho avuto modo di scrittura è un metodo che converte Oggetto array di byte.Il metodo è il seguente:
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
}
Questo metodo è il ritorno byte[]
correttamente.Ma, potrei convertirlo in un'immagine bitmap
BitmapFactory.decodeByteArray(blob,0,blob.length);
restituisce null
.quindi non poteva impostare imageview
.
Soluzione
Prova in questo modo.Questo potrebbe aiutare.
byte[] pic=(cursor.getBlob(position));
ByteArrayInputStream imageStream = new ByteArrayInputStream(pic);
Bitmap theImage= BitmapFactory.decodeStream(imageStream);