A blob refers to a binary large object. A BLOB usually comes into picture with Sqlite, ususally it is some data(image, audio file) which needs to be stored in a database purely on need basis. Although it is not a very good approach to do this but some times it is just the requirement. So actually, I demonstrate here to store an icon image into the android sqlite as a BLOB(byte array) and then retrieve and show it on the screen.

    • Step 1 would be to convert the image into a byte array,

 

Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.icon); ByteArrayOutputStream bos = new ByteArrayOutputStream(); bitmap.compress(CompressFormat.PNG, 0 /*ignored for PNG*/, bos); byte[] bitmapdata = bos.toByteArray();

    • Step 2 would be to store this in the database,

 

SQLiteDatabase db=this.openOrCreateDatabase(“imagedatabase”, this.MODE_PRIVATE, null); db.execSQL(“CREATE TABLE IF NOT EXISTS imagetable (“ + “_id INTEGER PRIMARY KEY AUTOINCREMENT,” + “image BLOB” + “);”); ContentValues values = new ContentValues(); values.put(“image”, bitmapdata); long row_id=db.insert(“imagetable”, null, values);

    • Step 3 would be to retrieve and display it back on screen,

 

Cursor cursor = db.query(“imagetable”, new String[]{“image”}, null, null, null, null,null); System.out.println(“—–getcolumn count”+cursor.moveToFirst()); //get it as a ByteArray byte[] mybyte=cursor.getBlob(0); //the cursor is not needed anymore cursor.close(); //convert it back to an image ByteArrayInputStream imageStream = new ByteArrayInputStream(mybyte); Bitmap theImage = BitmapFactory.decodeStream(imageStream); ((ImageView)findViewById(R.id.view_image)).setImageBitmap(theImage);

A simple 3 step process!