Search code examples
javaandroidandroid-roomandroid-architecture-components

How to avoid duplicating in Android Room


I want to create an app that stores the names of scooters, but when I search name, I am getting duplicates, I am using Room for Android, here is my code. Anyone please help me, thanks.

POJO Class

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

Dao Interface

@Query("SELECT * FROM BirdsRoom" )
List<BirdsRoom> getCachedBirds();

@Insert(onConflict = OnConflictStrategy.REPLACE)
void insertBirds(BirdsRoom... birdsRoom);

How I insert data

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

Solution

  • If you want to be battery and code unique in your BirdsRoom to set annotation like below

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