0

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?

Tobias Moe Thorstensen
  • 8,861
  • 16
  • 75
  • 143

2 Answers2

1

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

Community
  • 1
  • 1
Nermeen
  • 15,883
  • 5
  • 59
  • 72
1

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

jeet
  • 29,001
  • 6
  • 52
  • 53