12

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 my create Database statement:

 DBAdapter class onCreate()
 db.execSQL("CREATE TABLE "+ITEMS_TABLE+" ( "+ COLUMN_ITEM_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COLUMN_ITEM_NAME +" TEXT, "+ COLUMN_ITEM_SPECS +" TEXT, " + COLUMN_ITEM_PRICE +
" NUMBER, " + COLUMN_ITEM_IMAGE + " BLOB, " + COLUMN_ITEM_QTY +" NUMBER)");

void AddItems(ItemsPojo itemsObj) 

{ 
     Log.i("in here", "item fields");           
     SQLiteDatabase db= DBHelper.getWritableDatabase(); 

    if (db==null) 
    { 
        Log.i("nulll", "mnllllsg"); 
    } 
    ContentValues cv=new ContentValues(); 
    cv.put(COLUMN_ITEM_NAME, itemsObj.getItemName()); 
    cv.put(COLUMN_ITEM_SPECS, itemsObj.getItemSpecs());
    cv.put(COLUMN_ITEM_PRICE, itemsObj.getItemPrice());
    cv.put(COLUMN_ITEM_QTY, itemsObj.getItemQty());
    cv.put(COLUMN_ITEM_IMAGE, itemsObj.getItemImg()); 




 long affectedColumnId = db.insert(ITEMS_TABLE, null, cv);
    db.close(); 

} 

public Bitmap  getAllImages() 
 { 
     SQLiteDatabase db=DBHelper.getWritableDatabase(); 




  //Cursor cur= db.rawQuery("Select "+colID+" as _id , "+colName+", "+colAge+" from "+employeeTable, new String [] {}); 
     Cursor cur= db.rawQuery("SELECT * FROM "+ITEMS_TABLE,null); 
     //if(cur.getCount() > 0){
         //Cursor c = mDb.query(" ... "); 
         cur.moveToFirst(); 




 ByteArrayInputStream inputStream = new ByteArrayInputStream(cur.getBlob(cur.getColumnIndex(COLUMN_ITEM_IMAGE))); 
         Bitmap b = BitmapFactory.decodeStream(inputStream); 
    // }
 return b;
 } 

In my Main Oncreate I populate my Database like this:

Bitmap image = BitmapFactory.decodeResource(getResources(), R.drawable.red_bn);       
        ByteArrayOutputStream out = new ByteArrayOutputStream();      
        image.compress(Bitmap.CompressFormat.PNG, 100, out); 

        byte[] b = out.toByteArray();   
        String name; 
        name="QUEEN_BED1"; 
        String specs = "blaBlaBla";
        double price = 5420;
        int qty = 10;
        ItemsPojo itemsObj = new ItemsPojo(name,specs,price,b,qty); 




    db.AddItems(itemsObj);

I am now stuck, please can anyone help me to retrieve this picture and display it on a gridview?

pb2q
  • 58,613
  • 19
  • 146
  • 147
user1427993
  • 123
  • 1
  • 1
  • 5
  • 2
    Save the images as files, and save the path to the file in the DB instead of storing the image in the DB – Kumar Bibek May 31 '12 at 09:49
  • Here are some good tutorials on saving **image** to database and retrieving it: [Tutorial 1](http://android-codes-examples.blogspot.com/2011/09/image-and-content-is-populated-from.html) [Tutorial 2](http://www.tutorialforandroid.com/2009/10/how-to-insert-image-data-to-sqlite.html) – Imran Rana May 31 '12 at 09:55
  • Kumar, do have a tutorial or maybe a sample code to do that, please help. – user1427993 May 31 '12 at 10:09

2 Answers2

15

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.

Jose L Ugia
  • 5,960
  • 3
  • 23
  • 26
  • Thanks, this would have taken me a while to figure out. All done in a matter of minutes thanks to you :) – HGPB Dec 01 '12 at 18:31
  • @JoseLUgia Thanks I followed Your Example But it Shows me a Error https://stackoverflow.com/questions/63610127/android-code-1-sqlite-error-no-colum-name-was-found – Karthickyuvan Aug 27 '20 at 15:11
1

It depends on how you want to store your Image, because you are storing as a byte array here is how to retrieve it

  public Cursor fetchAll() {
            return databaseHelper.query(ITEMS_TABLE, new String[] { COLUMN_ITEM_ID,   COLUMN_ITEM_NAME, COLUMN_ITEM_SPECS,COLUMN_ITEM_PRICE, COLUMN_ITEM_IMAGE,COLUMN_ITEM_QTY},null, null, null, null, null);
        }
/*    this method will give you a cursor with all the records of your database table now you need to parse these records on to objects*/

private List<ItemsPojo> parse(Cursor cursor) {
     List<ItemsPojo> toReturn = null;
     toReturn = new ArrayList<SignImage>();
     ItemsPojo obj;
     if (cursor.moveToFirst()) {
          while (cursor.isAfterLast() == false) {
               obj = new ItemsPojo();
               obj.setId(cursor.getInt(0));
               obj.setItemName(cursor.getString(1));
               obj.setItemSpecs(cursor.getString(2));
               obj.setItemPrice(cursor.getDouble(3));
               obj.setItemImg(cursor.getBlob(4));
               obj.setItemQuantity(cursor.getInt(5));
               toReturn.add(obj);
               cursor.moveToNext();
               }
     }return toReturn;
}

now you have a List with all your records on your database, now what you need to do is create a ListActivity and show all your objects on it, If you dont know how to do this please post your comment here or if you have any doubt about the procedure above

KDEx
  • 3,505
  • 4
  • 31
  • 39
B. TIger
  • 459
  • 3
  • 10
  • 27
  • do u know how to add this list to a gridview ?? – Chandrashekhar Sep 10 '12 at 12:46
  • I have done it using a ListActivity with a custom Adapter and a custom Row It's really clean and quick to do I would advise to do it this way instead of using a GridView do would you like to see this aproach – B. TIger Sep 10 '12 at 12:49
  • my requirement is to use gridview :) – Chandrashekhar Sep 10 '12 at 12:51
  • Well let me know if this link helps you the diference is the way you use your adapter instead of a list of drwables you manypulate a list of your objects and you set your image on the image view http://www.androidhive.info/2012/02/android-gridview-layout-tutorial/ – B. TIger Sep 11 '12 at 14:17