gpt4 book ai didi

java - 房间类型转换器不工作

转载 作者:行者123 更新时间:2023-12-02 02:21:12 24 4
gpt4 key购买 nike

我遇到 Room 无法识别我的转换器的问题。错误:

Cannot figure out how to save this field into database. You can consider adding a type converter for it.  

我需要在数据库中存储一些 map 和集合。我究竟做错了什么? room 不喜欢接口(interface)或泛型吗?
代码:(抱歉所有字段和类名,它们是英语和捷克语的混合体,与某些 java 类名称不同):
转换器(仅部分)

public class MyConverter {
/**
* makes a string like 1;2;3;5;4;8;1;6;8;4 from a collection of integers.
*/
@TypeConverter
public static @NonNull String toString(@NonNull Collection<Integer> c) {
StringBuilder sb = new StringBuilder();
for (Integer item : c) {
sb.append(item.toString() + ";");
}
sb.delete(sb.length()-1,sb.length()-1);
return sb.toString();
}

/**
* makes a Set<Integer> from string like 1;2;3;4;5;6
* @throws NumberFormatException on incorrect input
*/
@TypeConverter
public static@NonNull Set<Integer> toIntegerSet(@NonNull String s) {
Set<Integer> set = new LinkedHashSet<>();
String[] split = s.split(";");
try {
for (String item : split) {
set.add(Integer.parseInt(item));
}
}catch (NumberFormatException e){
throw new NumberFormatException("Could not make set of integers (like 1;2;3;8;7) from \"" + s +"\"");
}
return set;
}
}

数据库:

@Database(entities = {SQLUkol.class,SQLPredmet.class,SQLList.class},version = 1)
@TypeConverters({MyConverter.class})
public abstract class AppDatabase extends RoomDatabase {
public abstract MojeDAO mojeDao();
}

实体之一(不包括 getter、setter 和构造函数):

    @Entity(primaryKeys = {"id", "list_id"},
indices = {@Index("list_id")},
foreignKeys = @ForeignKey(entity = SQLList.class, parentColumns = "id",
childColumns = "list_id", onDelete = ForeignKey.CASCADE),
tableName = "ukols")
public class SQLUkol implements Comparable<SQLUkol> {
@ColumnInfo(name = "list_id")
private final int listID;
private final int id;
private String title;
@ColumnInfo(name = "title_changed")
private boolean titleChanged = false;
private String notes;
@ColumnInfo(name = "notes_changed")
private boolean notesChanged = false;
private boolean completed;
@ColumnInfo(name = "completed_changed")
private boolean completedChanged = false;
private LocalDate date;
@ColumnInfo(name = "date_changed")
private boolean dateChanged = false;
@Embedded
private final SQLData data;
}

最佳答案

Room 不太喜欢泛型。我必须这样做:

@TypeConverter
public static String toString1(Map<String, String> m){
...
}

@TypeConverter
public static String toString2(Map<Integer, String> m){
...
}

@TypeConverter
public static String toString3(Set<Integer> s){
...
}

@TypeConverter
public static String toString4(List<Integer> l){
...
}

不只是

@TypeConverter
public static String toString(Map m){
...
}

@TypeConverter
public static String toString(Collection<Integer> c){
...
}

关于java - 房间类型转换器不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48478704/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com