ORMLite and Images saved as BLOB on Android

Codejoy picture Codejoy · Jul 26, 2011 · Viewed 10.3k times · Source

So I recently switched my database stuff over to ORMLite in my android tablet application I am writing. So far so good, got most things refactored/recoded. Though I am having issues to what was originally stored in the database as a BLOB. In my original data model it looked like this:

byte[] imageBytes;

but I don't think I can use that in ORMLite, best I could tell it has to be a string so now I have:

@DatabaseField
String picture;

But now, I am confused as to how to read and write those data bits as bytes, etc...I was using code like this to ferry data to and from the database:

...
//Set the clients image to what was captured...
Bitmap resized2= android.graphics.Bitmap.createScaledBitmap(thumbnail, thumbnail.getWidth()/2, thumbnail.getHeight()/2, true);
ByteArrayOutputStream baos = new ByteArrayOutputStream();  
resized2.compress(Bitmap.CompressFormat.PNG, 100, baos); //bm is the bitmap object   
byte[] b = baos.toByteArray();  

mClient.setImageBytes(b);
myImage.setImageBitmap(resized2);
//do save to the database of the image to the blob whose column is picture
ContentValues initialValues = new ContentValues();
initialValues.put("picture", mClient.getImageBytes());
String [] strArray = {""+sid};
long n = dbAdapter.updateRecordsInDB("clients", initialValues, "_id=?", strArray);      

So now thats how I WAS saving the image, I am not sure how to do this if there are no BLOBS in the ORMLite and I have to use strings?

for completeness this is how i would display the image:

if(mClient.getImageBytes().length <= 1) //no image in database, thats fine use generic
    myImage.setImageResource(R.drawable.sillo); // create a sillouhtette face icon here...
else
    myImage.setImageBitmap((BitmapFactory.decodeByteArray(mClient.getImageBytes(),0, (mClient.getImageBytes()).length)));

So what do i have to do to get these images in and out of the database, and is the field type of String correct for a "Blob" ?

Answer

Gray picture Gray · Jul 26, 2011

You can indeed store byte[] fields in ORMLite. To quote the manual about byte arrays:

Array of bytes (byte[]) persisted as SQL type VARBINARY. This is different from the DataType.SERIALIZABLE type which serializes an object as an array of bytes.

NOTE: Because of backwards compatibility, any fields that are of type byte[] must be specified as DataType.BYTE_ARRAY or DataType.SERIALIZABLE using the dataType field and will not be auto-detected.

So, to use byte[] you will need to specify the type of the data:

@DatabaseField(dataType = DataType.BYTE_ARRAY)
byte[] imageBytes;

The trick is that ORMLite does not automatically detect the type of the byte[] because of some backwards compatibility issues.