Android ORM系列之GreenDao自訂類型轉換器與代碼混淆配置

來源:互聯網
上載者:User

Android ORM系列之GreenDao自訂類型轉換器與代碼混淆配置

有時候,我們的實體類中會有一些屬性,但是資料庫中沒有對應的類型,這個時候我們就需要自訂轉換器進行類型轉換。很常見的處理就是Date類型一般如果精度要求不高的話我們會轉換為Long類型進行儲存,讀取的的時候再講其轉換為Date類型。那麼如果我們想要讓它直接以時間字串儲存呢,這個也好辦,GreenDao為我們提供了自訂類型轉換的支援。

首先,我們需要實現PropertyConverter介面,實現裡面的兩個方法convertToEntityProperty和convertToDatabaseValue,該介面需要兩個泛型參數,第一個參數是實體類中的類型,第二個參數是資料庫中儲存的類型。現在假設我們需要將Date轉換為String進行儲存,那麼介面的實現應該是這樣的。

public class DateStringConverter implements PropertyConverter {    @Override    public Date convertToEntityProperty(String databaseValue) {        return null;    }    @Override    public String convertToDatabaseValue(Date entityProperty) {        return bull;    }}

接下來我們進行轉換

public class DateStringConverter implements PropertyConverter {    private static final String DEFAULT_FORMAT=yyyy-MM-dd HH:mm:ss;    @Override    public Date convertToEntityProperty(String databaseValue) {        return convert2Date(databaseValue,DEFAULT_FORMAT);    }    @Override    public String convertToDatabaseValue(Date entityProperty) {        return convert2String(entityProperty,DEFAULT_FORMAT);    }    public static String convert2String(Date date,String format){        String currentDate=null;        try {            SimpleDateFormat formatter=new SimpleDateFormat(format);            currentDate=formatter.format(date);        }catch (Exception e){            e.printStackTrace();        }        return currentDate;    }    public static Date convert2Date(String day, String format) {        if (day == null || format == null)            return null;        SimpleDateFormat formatter = new SimpleDateFormat(format);        try {            Date dt = formatter.parse(day);            return dt;        } catch (ParseException e) {            e.printStackTrace();        }        return null;    }}

之後產生實體類

Entity type = schema.addEntity(Demo);type.addStringProperty(test).customType(java.util.Date,cn.edu.zafu.greendao.db.converter.DateStringConverter);

addProperty的時候是對應的資料庫中的類型,這裡我們儲存為字串,所以是addStringProperty,然後通過customType函數指定實體類中的類型,這裡是java.util.Date,接著就是我們的類型轉換器的全類名。接著試試往資料庫中插入一條資料,我們會發現他直接以字串儲存了,

最後附帶一下混淆配置,給需要混淆的項目加入以下語句<喎?http://www.bkjia.com/kf/ware/vc/" target="_blank" class="keylink">vcD4NCjxwcmUgY2xhc3M9"brush:java;">-keepclassmembers class * extends de.greenrobot.dao.AbstractDao { public static java.lang.String TABLENAME;}-keep class **$Properties

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.