Gordy
Gordy

Reputation: 23

Android: Sqlite crashes from big blob

First post here, so please bear with me if I get something wrong.

I'm trying to store images for an application in an sqlite database. The images should be stored as blobs (is this a bad idea?). The code to do so looks like this:

public long createPicture(String title, byte [] thumb, byte [] imageData) {
    ContentValues data = new ContentValues();
    data.put(T_KEY_TITLE, title);            
    data.put(T_KEY_CONTENT, imageData);       // <-- blob in the db 
    data.put(T_KEY_THUMB, thumb);

    // db is an SQLiteDatabase
    return db.insert(TABLE_PICS, null, data); // <-- Crash occurs on this line
}

This code works perfectly well for the most part, but when I try to store large pictures (5 megapixels from the built in camera) it crashes. Not only does it crash, it also screws up the database so that the app crashes whenever I try to launch it again.

So my question is: is there any way to get around this, or should I put the large pictures as files and just store the path? Also, I'd love to get some general guidelines on when to use sqlite and when to just go for files.

Thanks! :)

Upvotes: 2

Views: 2761

Answers (2)

Jack
Jack

Reputation: 9252

I wouldn't recommend storing the entire image in the database. Instead why don't just store the image uri or path in the database, and store the actual image data in the content provider?

So to store your image it would be:

Uri u;
File fi = new File("/sdcard/tmp");
try {
    u = Uri.parse(android.provider.MediaStore.Images.Media.insertImage(getContentResolver(), fi.getAbsolutePath(), null, null));
    imageSaveName1 = u.toString();

}

You would store imageSaveName1 in the database, and then to retrieve use:

Bitmap b = android.provider.MediaStore.Images.Media.getBitmap(getContentResolver(), imageSaveName1);

Upvotes: 2

John Leehey
John Leehey

Reputation: 22240

For storing images, the usual and best practice is to store them externally (to an SD card, or some other means of external storage). getExternalStorageDirectory() will provide you with a location to store your large files, or getExternalFilesDir() if you're API 8 and above.

The database transaction could be having any number of things go wrong (insufficient space, transaction timeout, etc.). It's probably best to store the URI of the image in the DB, then place the actual image into an external location.

Upvotes: 2

Related Questions