如何避免在Android房间复制

n6lpvg4x  于 2023-02-20  发布在  Android
关注(0)|答案(2)|浏览(143)

我想创建一个应用程序,存储滑板车的名称,但当我搜索名称,我得到重复,我正在使用Android的房间,这里是我的代码。任何人请帮助我,谢谢。

  • POJO类 *
@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;
  • 道界面 *
@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);
njthzxwz

njthzxwz1#

如果你想在你的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;
bwleehnv

bwleehnv2#

如果你不想数值重复,你可以同样添加注解;

@Entity(
   tableName = "birds",
   indices = [
       Index("battery", unique = true),
       Index("code", unique = true)
   ]
)

相关问题