2016-06-27 23 views
1

我试图使用greendao生成器生成我的模型,我不太清楚如何添加接受List<String>如何添加列表<String>属性到我的greendao生成器?

属性我知道如何使用addToMany但什么添加List<Model>如果我需要将ArrayList存储在我的一个模型中?

事情是这样的:

Entity tags = schema.addEntity("Tags"); 
    tags.implementsInterface("android.os.Parcelable"); 
    tags.addLongProperty("tagId").primaryKey().autoincrement(); 
    tags.addLongProperty("date"); 
    tags.addArrayStringProperty("array"); // something like this 

我想创造另一个实体存储阵列的所有值,并做ToMany这样

Entity myArray = schema.addEntity("MyArray"); 
    myArray.implementsInterface("android.os.Parcelable"); 
    myArray.addLongProperty("myArrayId").primaryKey().autoincrement(); 
    myArray.addLongProperty("id").notNull().getProperty(); 
    Property tagId = myArray.addLongProperty("tagId").getProperty(); 

ToMany tagToMyArray = tag.addToMany(myArray, tagId); 
tagToMyArray.setName("tags"); 
myArray.addToOne(tag, tagId); 

回答

4

可以连载该ArrayList和然后保存为greenDAO表中的字符串属性。

String arrayString = new Gson().toJson(yourArrayList); 

,然后检索回来这样

Type listType = new TypeToken<ArrayList<String>>(){}.getType(); 
List<String> arrayList = new Gson().fromJson(stringFromDb, listType) 
+0

感谢这么简单的答案 – Haroon

2

另一个way.You可以使用@convert注解。

@Entity 
public class User { 
@Id 
private Long id; 

@Convert(converter = RoleConverter.class, columnType = Integer.class) 
private Role role; 

public enum Role { 
    DEFAULT(0), AUTHOR(1), ADMIN(2); 

    final int id; 

    Role(int id) { 
     this.id = id; 
    } 
} 

public static class RoleConverter implements PropertyConverter<Role, Integer> { 
    @Override 
    public Role convertToEntityProperty(Integer databaseValue) { 
     if (databaseValue == null) { 
      return null; 
     } 
     for (Role role : Role.values()) { 
      if (role.id == databaseValue) { 
       return role; 
      } 
     } 
     return Role.DEFAULT; 
    } 

    @Override 
    public Integer convertToDatabaseValue(Role entityProperty) { 
     return entityProperty == null ? null : entityProperty.id; 
    } 
} 
} 
相关问题