Albert Zheng
Albert Zheng

Reputation: 21

how to add custom property type in greendao

I am a new android programmer. Currently I am using Greendao. I noticed that it only provides certain add properties methods. I am wondering if there is any way to add other custom property types(For example, a Picture) to my entity? Thanks in advance.

Upvotes: 2

Views: 1943

Answers (1)

AlexS
AlexS

Reputation: 5345

Since greendao is open source you may very well implement such custom property types and map them to the basic SQLite-datatypes. But you shouldn't!

  1. If you do you will have to merge your solution into the greendao sources everytime you want to use a new version/release of greendao.
  2. Greendao covers as far as I know already all SQLite-datatypes with its properties.

To save pictures or other complex data you can use the ByteArray-property:

Entity entity = schema.addEntity("MyTest");
entity.addByteArrayProperty("picture");

In the KEEP-SECTION of your entity you can add conversion methods:

public static byte[] bitmap2bytes(Bitmap bitmap) {
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
    return stream.toByteArray();
}

public static Bitmap bytes2Bitmap(byte[] byteArray) {
    return BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
}

And finally use:

myTestObj.setPicture(MyTest.bitmap2bytes(bitmap));

and

Bitmap bmp = MyTest.bytes2bitmap(myTestObj.getPicture());

Remark: In case of pictures or other big data you can follow the approach to store the data as file on the device and store the path to that file in your database using String-property.

Upvotes: 3

Related Questions