【问题标题】:How to avoid duplicating in Android Room如何避免在 Android Room 中重复
【发布时间】:2018-10-12 13:20:41
【问题描述】:

我想创建一个存储滑板车名称的应用程序,但是当我搜索名称时,我得到了重复,我使用的是 Android 版 Room,这是我的代码。哪位大神帮帮忙,谢谢。

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);

【问题讨论】:

  • 通过调用insertBirds分享有关如何存储数据的代码。
  • 我已经分享了代码,Birds类和BirdLocation类是我改造的POJO类,BirdsRoom是实体类

标签: java android android-room android-architecture-components


【解决方案1】:

如果您想成为 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;

【讨论】:

  • 它给了我这个错误:android.database.sqlite.SQLiteConstraintException: UNIQUE constraint failed: BirdsRoom.code (code 2067)
  • 当您的 BirdsRoom 已经存在并且您更改 BirdsRoom 时,您必须迁移数据库或卸载应用程序并使用新的 BirdsRoom 重新安装
  • 不,它没有帮助,第一次运行成功,但第二次运行给出提到的错误
  • 谢谢我已经添加(onConfict = ConflictStrategy.REPLACE)它有帮助,非常感谢
猜你喜欢
  • 2018-09-24
  • 1970-01-01
  • 1970-01-01
  • 2019-02-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-08
  • 2021-01-13
相关资源
最近更新 更多