项目中一些地方用到了数据库操作,在此总结一下
1.先记录一个查看数据库的小工具
https://github.com/amitshekhariitbhu/Android-Debug-Database
之前查看数据库都是在data/data目录下把数据库导出来然后通过SQLite可视化工具查看表中的内容,这样可能会就比较麻烦。这个工具可以直接访问浏览器查看表的内容,相当于把自己的手机当作服务器然后访问,查看的时候直接访问手机上的ip地址:8080即可。具体的使用看文档的说明就行。
2.GreenDao存储自定义类型数据
在项目里遇到两种
1.存储枚举类型的
2.存储自定义类型的
这两种都可以转换成我们需要的类型存储到数据库中。greendao只支持boolean, Boolean int, Integer short, Short long, Long float, Float double, Double byte, Byte char, Character byte[] String Date
这几种基本类型。我们可以看下https://docs.objectbox.io/advanced/custom-types只要是我们自定义的类型最后存储到数据库中都只能是这些类型。对于枚举我都转换成了String类型,如果需要转换成int类型可以参考http://greenrobot.org/greendao/documentation/custom-types/ 。然后我们来实现PropertyConverter接口,这个接口需要传入两个泛型,第一个是实体的类型,第二个是数据库中的类型。然后实现里面的两个方法convertToEntityProperty和convertToDatabaseValue来转换成对应的类型。
@Entity
public class Message {
@Id
private String uid;
//枚举类型
@Convert(converter = ConversationTypeConverter.class, columnType = String.class)
private ConversationType conversationType;
//自定义类型
@Convert(converter = MsgBodyConverter.class, columnType = String.class)
private MsgBody body;
public enum ConversationType {
DEFAULT ,PRIVATE , GROUP ;
}
public class MsgBody {
private String msg;
private String extra;
}
public static class ConversationTypeConverter implements PropertyConverter<ConversationType, Integer> {
//将String值转换成ConversationType 值
@Override
public ConversationType convertToEntityProperty(Integer databaseValue) {
if (databaseValue == null) {
return null;
}
return ConversationType.valueOf(databaseValue);
}
//将ConversationType 值转换成String值
@Override
public Integer convertToDatabaseValue(ConversationType entityProperty) {
return entityProperty.name();
}
}
public static class MsgBodyConverter implements PropertyConverter<MsgBody , String> {
@Override
public MsgBody convertToEntityProperty(String databaseValue) {
if (databaseValue == null) {
return null;
}
return new Gson().fromJson(databaseValue, MsgBody .class);
}
@Override
public String convertToDatabaseValue(MsgBody entityProperty) {
if (entityProperty == null) {
return null;
}
return new Gson().toJson(entityProperty);
}
}