独特约束失败的房间数据库android

时间:2018-05-28 02:11:29

标签: android sqlite android-room

我遇到了Room数据库的问题,当我尝试使用我在Dao Class中声明的insert方法将数据写入数据库时​​出现此错误:

  

唯一约束失败

任何想法?

Dao Class

@Dao
public interface TaskDao {

    @Query("SELECT * FROM task")
    List<Task> getall();

    @Insert
    void insert(Task task);

    @Delete
    void delete(Task task);
}

AppDatabase类

@Database(entities = {Task.class}, version = 1)
public abstract class AppDatabase extends RoomDatabase {
    public abstract TaskDao mTaskDao();
}

模型类

@Entity
public class Task {

    @PrimaryKey
    private int uid;

    @ColumnInfo(name = "task_name")
    private String mName;

    @ColumnInfo(name = "task_box")
    private Integer mBox;

    @ColumnInfo(name = "is_done")
    private Integer mIsDone;
}

2 个答案:

答案 0 :(得分:1)

我弄明白,这个错误是因为数据中没有唯一值(在primaryKey中)所以我自动生成它,

模型类

@Entity
public class Task {
    @PrimaryKey(autoGenerate = true)
    private int uid;
    ...
}

答案 1 :(得分:1)

AppDatabase类

@Database(entities = {Task.class}, version = 1, exportSchema = false)
public abstract class AppDatabase extends RoomDatabase {
    public abstract TaskDao mTaskDao();
}

模型类

@Entity
public class Task {

    @PrimaryKey(autoGenerate = true)
    private int uid;

    @ColumnInfo(name = "task_name")
    private String mName;

    @ColumnInfo(name = "task_box")
    private Integer mBox;

    @ColumnInfo(name = "is_done")
    private Integer mIsDone;
}