Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

sqlite - Unique constraint failed room database android

I'm facing a problem with Room database, when trying to use insert method that I declared in Dao Class to write a data into database this error shows up:

Unique constraint failed

Any idea way?

Dao Class

@Dao
public interface TaskDao {

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

    @Insert
    void insert(Task task);

    @Delete
    void delete(Task task);
}

AppDatabase Class

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

Model Class

@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;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I figure it out, that error because there is no unique value in data (in primaryKey) so I make it auto generated,

Model Class

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...