Java 在文件室库中保存类变量

Java 在文件室库中保存类变量,java,android,database,android-room,Java,Android,Database,Android Room,大家好,我想在数据库中保存一个类变量,但收到以下错误: error: Cannot figure out how to save this field into database. You can consider adding a type converter for it. 这是我的桌子: @Entity(tableName = "tbl_projects") public class Room_Database_Project {

大家好,我想在数据库中保存一个类变量,但收到以下错误:

 error: Cannot figure out how to save this field into database. You can consider adding a type 
 converter for it.
这是我的桌子:

     @Entity(tableName = "tbl_projects")
     public class Room_Database_Project {
     @PrimaryKey(autoGenerate = true)
     private int id;
     private Project project;  
项目变量无法使。。。
我能做什么?

你可以用两种方法来做。看看什么更适合你的情况

类型转换器:定义类型转换器后,您可以在实体和DAO中使用自定义类型,就像使用基本类型一样

例如:

public static class Converters {
    @TypeConverter
    public Date fromTimestamp(Long value) {
        return value == null ? null : new Date(value);
    }

    @TypeConverter
    public Long dateToTimestamp(Date date) {
        if (date == null) {
            return null;
        } else {
            return date.getTime();
        }
    }

    @TypeConverter
    public Project fromString(String value) {
        return new Gson().fromJson(value, Project.class);
    }

    @TypeConverter
    public String fromProject(Project project) {
        return new Gson().toJson(project);
    }
}
public class Project {
     double projectLatitude;
     double ProjectLongitude;
    String projectName;
   }




@Entity(tableName = "tbl_projects")
     public class Room_Database_Project {
     @PrimaryKey(autoGenerate = true)
     private int id;
     @Embedded
     private Project project;  
    }
然后,您可以在抽象RoomDatabase类上添加
@TypeConverters(Converters.class)
注释

Embedded:此注释表示嵌入的类的实例存储为使用注释的类的固有部分

例如:

public static class Converters {
    @TypeConverter
    public Date fromTimestamp(Long value) {
        return value == null ? null : new Date(value);
    }

    @TypeConverter
    public Long dateToTimestamp(Date date) {
        if (date == null) {
            return null;
        } else {
            return date.getTime();
        }
    }

    @TypeConverter
    public Project fromString(String value) {
        return new Gson().fromJson(value, Project.class);
    }

    @TypeConverter
    public String fromProject(Project project) {
        return new Gson().toJson(project);
    }
}
public class Project {
     double projectLatitude;
     double ProjectLongitude;
    String projectName;
   }




@Entity(tableName = "tbl_projects")
     public class Room_Database_Project {
     @PrimaryKey(autoGenerate = true)
     private int id;
     @Embedded
     private Project project;  
    }

您需要创建一个类型转换器类,如下所示:或:如果解决方案有帮助,请升级。如果解决方案有帮助,请升级