我试图玩游戏并了解Android的Room持久性库。到目前为止,我已经了解了如何插入内容并查询它们,但是现在我尝试使用2个构造函数,以便在我不想要的情况下不插入字段。
这样的事情:
public ImageData(int id, String name, String title, String description, int locationId) {
.....
public ImageData(int id, String name, String title, String description) {
在某些情况下,我没有位置,因此我不想在该位置列中插入任何内容。这是实现它的正确方法(显然不是因为我得到错误)吗?
Error:(38, 12) error: Room cannot pick a constructor since multiple constructors are suitable. Try to annotate unwanted constructors with @Ignore.
如果您需要更多信息,请与我们联系。
编辑:
@Entity(primaryKeys = {"id", "name"},
foreignKeys = @ForeignKey(entity = Location.class,
parentColumns = "id",
childColumns = "location_id",
onDelete=CASCADE))
public class ImageData {
@NonNull
public int id;
@NonNull
public String name;
public String title;
public String description;
public String time;
@ColumnInfo(name = "location_id")
@Nullable
public int locationId;
public ImageData(int id, String name, String title, String description, int locationId) {
this.id = id;
this.name = name;
this.title = title;
this.description = description;
this.locationId = locationId;
}
public ImageData(int id, String name, String title, String description) {
this.id = id;
this.name = name;
this.title = title;
this.description = description;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getName() {
return title;
}
public void setName(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getLocationId() {
return locationId;
}
public void setLocationId(int locationId) {
this.locationId = locationId;
}
}
@Entity
public class Location {
@PrimaryKey(autoGenerate = true)
public int id;
public double latitude;
public double longitude;
public Location(double latitude, double longitude) {
this.latitude= latitude;
this.longitude= longitude;
}
public int getId() {
return this.id;
}
}
答案 0 :(得分:1)
方法1
尝试使用if语句确定位置字段为空或在其中包含数据的位置,并根据结果使用构造函数。
修改强>
所以基本上,Room database
只允许你一次使用一个构造函数,所以在你的情况下,只需删除一个没有位置的构造函数。这将消除错误,但是当您向数据库添加新行时,如果您不想传递位置ID,请使用此行。
database.objectDAO.addObject(id, name, title, description, null);
答案 1 :(得分:1)
尝试对可以具有空值的实体字段使用默认值注释,例如:@ColumnInfo(defaultValue = "CURRENT_TIMESTAMP")
答案 2 :(得分:0)
您应该进行以下更改,您可以使用@ignore注释。
public ImageData(int id, String name, String title, String description, int locationId) {
this.id = id;
this.name = name;
this.title = title;
this.description = description;
this.locationId = locationId;
}
@Ignore
public ImageData(int id, String name, String title, String description) {
this.id = id;
this.name = name;
this.title = title;
this.description = description;
}
答案 3 :(得分:0)
使用Integer类而不是int。
对于布尔值而不是布尔值也是如此