by JoyLakh » Wed Apr 08, 2009 2:12 pm
Hello guys,
I managed to come up with a solution and I want to share it with you as it took me relatively long time and I dont want anyone to loose time on this. In the below pasted code, I created a database(myCoolDB_21) and inserted an image(source.jpg) in its table(images). I used the sql datatype blob( binary large object ), so that I can store the image in the form of bytes. To confirm that I have successfully inserted the image in the database, I retrieved it and made a copy of it(first copy.jpg).
Only pre-requisite is virtual sd-card with source.jpg in it, and here goes the code:
public class DataBaseWork extends ListActivity
{
private final String MY_DATABASE_NAME = "myCoolDB_21";
private final String MY_DATABASE_TABLE = "images";
private static final String DATABASE_CREATE =
"create table images (_id integer , image blob );";
public static final String KEY_IMAGE = "image";
public static final String KEY_ROWID = "_id";
// Called when the activity is first created.
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
SQLiteDatabase myDB = null;
try
{
myDB = this.openOrCreateDatabase(MY_DATABASE_NAME, MODE_PRIVATE, null);
FileInputStream fis = new FileInputStream("/sdcard/source.jpg");
byte[] hash = new byte[fis.available()];
fis.read(hash);
fis.close();
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_IMAGE, hash);
myDB.execSQL(DATABASE_CREATE);
myDB.insert(MY_DATABASE_TABLE, null, initialValues);
Cursor c = myDB.query(MY_DATABASE_TABLE, new String[] {KEY_ROWID, KEY_IMAGE}, null, null, null, null, null);
// Get the indices of the Columns we will need
int imageColumn = c.getColumnIndex("image");
// Check if our result was valid.
if (c != null)
{
// Check if at least one Result was returned.
if (c.getCount()!=0)
{
c.moveToFirst();
// Loop through all Results
do
{
FileOutputStream fos = new FileOutputStream("/sdcard/firstCopy.jpg");
fos.write(c.getBlob(imageColumn));
fos.flush();
fos.close();
} while (c.moveToNext());
}
}
} catch(Exception ex){
}finally{
if (myDB != null)
{
myDB.close();
SQLiteDatabase.releaseMemory();
}
}
}
}
Celebrate Life.