I am new to android. I created a table that has an itemName,Price and image. I am trying to retrieve the image and name fields and display them on a gridview
Here is
The most efficient (and btw, most straight forward approach) is to save a bytearray of the image in your local database. For that you'll just need to use a TEXT datatype in your database. Like this:
CREATE TABLE IF NOT EXISTS Your_table ( id INTEGER PRIMARY KEY NOT NULL UNIQUE, someOtherField TEXT, pictureData TEXT);
There's one seamless way to avoid dealing with conversions: Just convert to Bitmap and back to bytearray in your setters and getters in such a way that you don't need to care about that in the whole dev cycle. Let's go for an example. Let's say you have an object user which is stored in your localDB for which you have an avatar.
public class User {
private String email;
private String name;
private Drawable pictureDataDrawable;
public User() {}
public void setPictureData(byte[] pictureData) {
pictureDataDrawable = ImageUtils.byteToDrawable(pictureData);
}
public byte[] getPictureData(){
return ImageUtils.drawableToByteArray(pictureDataDrawable);
}
}
And wherever you retrieve your data from DB it'll be enough with adding something like that:
user.setPictureData(cursor.getBlob(cursor.getColumnIndexOrThrow(DB_PICTURE_DATA_KEY)));
For the opposite way (writing the drawable to DB):
ContentValues c = new ContentValues();
c.put(DB_PICTURE_DATA_KEY, user.getPictureData());
...
Finally two easy methods in your ImageUtils to convert back and forth:
public static byte[] drawableToByteArray(Drawable d) {
if (d != null) {
Bitmap imageBitmap = ((BitmapDrawable) d).getBitmap();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
imageBitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] byteData = baos.toByteArray();
return byteData;
} else
return null;
}
public static Drawable byteToDrawable(byte[] data) {
if (data == null)
return null;
else
return new BitmapDrawable(BitmapFactory.decodeByteArray(data, 0, data.length));
}
And you're good to go.