Tobias Moe Thorstensen
Tobias Moe Thorstensen

Reputation: 8981

SQLite database, objects with Bitmap

I have a problem regarding inserting objects to a SQLite database. My class, Case looks like this:

public class Case {

String caseNumber; 
int status; 
String date;
Bitmap rightIndexFinger;
Bitmap leftIndexFinger; 


public Case(String caseNumber, int status, String date, Bitmap rightIndexFinger, Bitmap leftIndexFinger) {

    this.caseNumber = caseNumber;
    this.status = status;
    this.date = date;
    this.rightIndexFinger = rightIndexFinger;
    this.leftIndexFinger = leftIndexFinger; 

}

public Case(String caseNumber, int status, String date) {

    this.caseNumber = caseNumber;
    this.status = status;
    this.date = date;
}


public Bitmap getRightIndexFinger() {
    return rightIndexFinger;
}


public void setRightIndexFinger(Bitmap rightIndexFinger) {
    this.rightIndexFinger = rightIndexFinger;
}


public Bitmap getLeftIndexFinger() {
    return leftIndexFinger;
}


public void setLeftIndexFinger(Bitmap leftIndexFinger) {
    this.leftIndexFinger = leftIndexFinger;
}


public String getCaseNumber() {
    return caseNumber;
}


public void setCaseNumber(String caseNumber) {
    this.caseNumber = caseNumber;
}


public int getStatus() {
    return status;
}


public void setStatus(int status) {
    this.status = status;
}


public String getDate() {
    return date.toString();
}


public void setDate(String date) {
    this.date = date;
}
}

I need to insert objects of this class into a SQLite database. What I tried is:

String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CASES + "("
                + KEY_ID + " INTEGER PRIMARY KEY," + DATE + " TEXT,"
                + RIGHTFINGER + " TEXT," + LEFTFINGER +" TEXT" + ")";
        db.execSQL(CREATE_CONTACTS_TABLE);

This make sense if all of my variables in the case class was String, but how can I do this for Bitmaps?

Upvotes: 0

Views: 3806

Answers (2)

jeet
jeet

Reputation: 29199

Convert Bitmap to Byte Array, and then save this byte array into database in Blob datatype. By folloqing code:

To convert a bitmap to byte array use following code:

Bitmap image = BitmapFactory.decodeResource(getResources(), R.drawable.thumbnail);

ByteArrayOutputStream out = new ByteArrayOutputStream();

image.compress(Bitmap.CompressFormat.PNG, 100, out);

byte[] buffer=out.toByteArray();

To save a byte array in blob type use following code:

ContentValues cv=new ContentValues();
   cv.put(CHUNK, buffer);       //CHUNK blob type field of your table
   long rawId=database.insert(TABLE, null, cv); //TABLE table name

Read more about Blob by this link

Upvotes: 1

Nermeen
Nermeen

Reputation: 15973

The bitmaps in sqlite are mapped to Blobs, to insert an image you insert it as a byte[]..
check https://stackoverflow.com/a/4508531/1434631
And https://stackoverflow.com/a/7331698/1434631

Upvotes: 1

Related Questions