I want to save Images in my database but I am not sure of one thing
I have this method on the class that extends SQLiteOpenHelper
public boolean insertDemo(byte[] a, byte[] b, byte[] c, byte d) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("id", 1);
cv.put("demo1", a);
cv.put("demo2", b);
cv.put("demo3", c);
cv.put("demo4", d);
db.insert("demo_tb", null, cv);
return true;
}
My question is,what should the datatype be? currently I have
db.execSQL("create table demo_tb"+"(id integer primary key,demo1 text,demo2 text,demo3 text,demo4 text)");
in the onCreate method.
for saving Images in sqlite database you should use BLOB datatype for that column in your table.
I use the BLOB type, I do not see with good eyes use TEXT type to save an array of bytes
Like this:
protected static final String CREATE_TABLE_IMAGE =
"CREATE TABLE IMAGES"
+ "("
+ " IMAGE_ID"
+ " INTEGER PRIMARY KEY ,"
+ " IMAGE_BLOB"
+ " BLOB "
+")";
public void CreateTable(String strCreate){
SQLiteDatabase db = getWritableDatabase();
db.execSQL(strCreate);
}
public boolean saveBytes(byte[] bytes, int id){
boolean ret = false;
SQLiteDatabase db = getWritableDatabase();
db.beginTransaction();
try{
String sql = "INSERT INTO IMAGES "
+ " ( IMAGE_ID"
+ ", IMAGE_BLOB"
+ " ) VALUES(?,?)";
SQLiteStatement insertStmt = db.compileStatement(sql);
insertStmt.clearBindings();
insertStmt.bindLong(1, id);
insertStmt.bindBlob(2, bytes);
insertStmt.executeInsert();
db.setTransactionSuccessful();
db.endTransaction();
ret = true;
}catch(Exception e){
e.printStackTrace();
ret = false;
}
return ret;
}
public byte[] getBytes( int id) throws Exception {
byte[] ret = null;
try {
String selectQuery = "SELECT I.IMAGE_BLOB "
+ " FROM IMAGES I WHERE I.IMAGE_ID = ?";
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery(selectQuery,new String[]{String.valueOf(id)});
if (!c.isClosed() && c.moveToFirst() && c.getCount() > 0) {
if (c.getBlob(c.getColumnIndex("IMAGE_BLOB")) != null)
{
ret = c.getBlob(c.getColumnIndex("IMAGE_BLOB"));
}
c.close();
if (db != null && db.isOpen())
db.close();
}
System.gc();
} catch (Exception e) {
System.gc();
throw e;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With