我试图创建一个整数id作为主键,然后它要求我创建getter和setter方法,然后它希望我动态设置id,但是我不想在我的应用中添加id字段,如果我必须自己设置id,autoGenerate的用途是什么?
import android.arch.persistence.room.ColumnInfo;
import android.arch.persistence.room.Entity;
import android.arch.persistence.room.PrimaryKey;
import android.support.annotation.NonNull;
@Entity(tableName = "messages")
public class Message {
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "message_date")
private String date;
@ColumnInfo(name = "message_timeHour")
private String timeHour;
@ColumnInfo(name = "message_timeMinute")
private String timeMinute;
@ColumnInfo(name = "message_contactName")
private String contactName;
@ColumnInfo(name = "message_text")
private String text;
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getTimeHour() {
return timeHour;
}
public void setTimeHour(String timeHour) {
this.timeHour = timeHour;
}
public String getTimeMinute() {
return timeMinute;
}
public void setTimeMinute(String timeMinute) {
this.timeMinute = timeMinute;
}
public String getContactName() {
return contactName;
}
public void setContactName(String contactName) {
this.contactName = contactName;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}
这是什么意思以及如何解决?
答案 0 :(得分:1)
每个@Entity必须至少有一个主键。
@PrimaryKey(autoGenerate = true)
您应该将其用作
@PrimaryKey(autoGenerate = true)
private int id;
此外,您应该为此id变量设置一个setter,以便当Room需要设置主键值时,它将使用您的setter方法,因为您的id变量是私有的。因此,在这种情况下,您根本不需要设置ID。房间会照顾好它。
答案 1 :(得分:0)