问题
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?
回答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;
}
}
回答2:
Most of the times you can't use the converter to produce a String since they are complex objects!
To not repeat the answer, in the other same question you can read my answer.
来源:https://stackoverflow.com/questions/44399380/room-persistence-library-nested-object-with-listvideo-embedded-doesnt-wor