【问题标题】:Room Persistence library - Nested Object with List<Video>, @Embedded doesn't work.房间持久性库 - 带有 List<Video> 的嵌套对象,@Embedded 不起作用。
【发布时间】:2017-11-08 00:34:06
【问题描述】:

我有一个 VideoList 对象,我想使用房间库保存它,但是当我尝试将 @Embedded 与 public List list = null 一起使用时;它给了我以下错误:错误:(23、24)错误:无法弄清楚如何将此字段保存到数据库中。您可以考虑为其添加类型转换器。

VideoList 类如下。

@Entity
public class VideoList {


@PrimaryKey
public String id;

public String title;
public String viewType;
public Integer sortingOrder = null;
public String componentSlug;
public String endPoint = null;

@Embedded
public List<Video> list = null;
public boolean hidden = false; }




Any suggestions? 

【问题讨论】:

标签: java android database sqlite android-database


【解决方案1】:

我认为Convertor是这种嵌套列表对象中最好的解决方案。

public class Converter {

public static String strSeparator = "__,__";

@TypeConverter
public static String convertListToString(List<Video> video) {
    Video[] videoArray = new Video[video.size()];
    for (int i = 0; i <= video.size()-1; i++) {
         videoArray[i] = video.get(i);
    }
    String str = "";
    Gson gson = new Gson();
    for (int i = 0; i < videoArray.length; i++) {
        String jsonString = gson.toJson(videoArray[i]);
        str = str + jsonString;
        if (i < videoArray.length - 1) {
            str = str + strSeparator;
        }
    }
    return str;
}

@TypeConverter
public static List<Video> convertStringToList(String videoString) {
    String[] videoArray = videoString.split(strSeparator);
    List<Video> videos = new ArrayList<Video>();
    Gson gson = new Gson();
    for (int i=0;i<videoArray.length-1;i++){
        videos.add(gson.fromJson(videoArray[i] , Video.class));
    }
    return videos;
}

}

【讨论】:

  • 我尝试对嵌套对象使用转换器,但处理时间显着增加(甚至比改造响应慢),意味着性能不佳!
  • 我明白了!有趣的。对我来说并没有太大变化。比方说,你是对的,那么你的建议是什么?与@relation 有什么关系?
  • 我没有为这种情况找到更好的解决方法,只是在 Room 上玩一会儿。我目前的工作是使用 Realm,非常好,非常快,而且非常简单。
  • 最好在 convertStringToList 方法中使用 for 循环:for (int i=0;i
猜你喜欢
  • 2019-11-18
  • 2017-10-23
  • 2019-08-08
  • 1970-01-01
  • 2017-11-18
  • 1970-01-01
  • 2017-10-29
  • 2018-05-27
  • 2018-01-22
相关资源
最近更新 更多