2016-06-27 22 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; 
    } 
} 
} 
相關問題