Java 如何避免在Android Room中复制
我想创建一个应用程序来存储滑板车的名称,但当我搜索名称时,我会得到重复的名称,我使用的是Android的Room,这是我的代码。任何人请帮助我,谢谢 波乔班 Dao接口Java 如何避免在Android Room中复制,java,android,android-room,android-architecture-components,Java,Android,Android Room,Android Architecture Components,我想创建一个应用程序来存储滑板车的名称,但当我搜索名称时,我会得到重复的名称,我使用的是Android的Room,这是我的代码。任何人请帮助我,谢谢 波乔班 Dao接口 如果你想在你的鸟舍里保持电池和代码的唯一性,可以设置如下注释 @Entity(indices = {@Index(value = {"battery", "code"}, unique = true)}) public class BirdsRoom { @PrimaryKey(autoGenerate = true) pri
如果你想在你的鸟舍里保持电池和代码的唯一性,可以设置如下注释
@Entity(indices = {@Index(value = {"battery", "code"}, unique = true)})
public class BirdsRoom {
@PrimaryKey(autoGenerate = true)
private int id;
@ColumnInfo(name = "battery")
private String battery;
@ColumnInfo(name = "code")
private String birdCode;
@ColumnInfo(name = "latitude")
private double lat;
@ColumnInfo(name = "longitude")
private double lng;
通过调用
insertBirds
共享有关如何存储数据的代码。我已经共享了代码,Birds类和BirdLocation类是我的改装POJO类,BirdsRoom是entitiy classIt它给了我以下错误:android.database.sqlite.SQLiteConstraintException:唯一约束失败:BirdsRoom.code(代码2067)当您的BirdsRoom已准备就绪并且您更改了BirdsRoom时,您必须迁移数据库或uninstal应用程序,然后使用新的BirdsRoom重新安装。不,这没有帮助,第一次运行成功,但第二次运行失败。感谢我添加了(onconfig=ConflictStrategy.REPLACE)它有帮助,非常感谢
@Query("SELECT * FROM BirdsRoom" )
List<BirdsRoom> getCachedBirds();
@Insert(onConflict = OnConflictStrategy.REPLACE)
void insertBirds(BirdsRoom... birdsRoom);
Birds birds = response.body().getBirdsList().get(i);
BirdLocation birdLocation = birds.birdLocation;
BirdLocation location = birds.birdLocation;
BirdsRoom birdsRoom = new BirdsRoom(birds.getCode(),birds.getBatteryLevel(),
birdLocation.getLat(), birdLocation.getLng());
birdsDatabase.getUserDao().insertBirds(birdsRoom);
@Entity(indices = {@Index(value = {"battery", "code"}, unique = true)})
public class BirdsRoom {
@PrimaryKey(autoGenerate = true)
private int id;
@ColumnInfo(name = "battery")
private String battery;
@ColumnInfo(name = "code")
private String birdCode;
@ColumnInfo(name = "latitude")
private double lat;
@ColumnInfo(name = "longitude")
private double lng;