Room Persistence library - Nested Object with List<Video>, @Embedded doesn't work.
Asked Answered
F

1

5

I have a VideoList object which I want to save using room library but when i try to use @Embedded with public List list = null; it is giving me below error: Error:(23, 24) error: Cannot figure out how to save this field into database. You can consider adding a type converter for it.

VideoList Class is as below.

@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? 
Francefrancene answered 6/6, 2017 at 20:35 Comment(3)
I think @Embedded only works with primitives, things that would go into individual columns in the table for VideoList. AFAIK, you would need to have a Video entity with its own table and a foreign key back to the list.Moneychanger
The answer you #44330952Thetos
What you are looking for is thisThetos
F
1

I think Convertor is the best solution in this kind of nested list objects.

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;
}

}

Francefrancene answered 7/6, 2017 at 21:43 Comment(4)
I tried to use converters for nested object but processing time significant increased (even slower than retrofit response), mean bad performance!Theosophy
I see! Interesting. It didn't change much for me. Let's say, you are right then what do you propose? Something with @relation?Francefrancene
i didn't find a better workaround for this situation, just play on Room for a while. My current work's using Realm, really good, very fast, and so easy.Theosophy
Better make the for-loop in the convertStringToList method: for (int i=0;i<videoArray.length;i++) instead of length-1 to possibly prevent other developers from a lot of time spending on bugfixingSorilda

© 2022 - 2024 — McMap. All rights reserved.