Search code examples
javaandroidsqliteandroid-room

How to avoid duplicate data entry in a table in Room Db?


I am using RoomDb to store the messages in the device using room database. Each Message contain a unique Id which is generated when storing message on a server. When a message is downloaded and stored in a Room database and again if I try to download the message it again gets downloaded and saved to room db.

I tried using replace strategy, but still it doesnt works

 @Insert(onConflict = OnConflictStrategy.REPLACE)
    void saveMessage(ArrayList<Message> messages);

The above code is supposed to replace the existing message, but its not doing so.

Message model looks like this.

public class Message {

    @Exclude
    @PrimaryKey(autoGenerate = true)
    public long _id;

    @Exclude
    @ColumnInfo(name = "messageId")
    public String id;

    @Exclude
    public boolean outbox;
    @Exclude
    public boolean pending;

    @Exclude
    public boolean draft;

    @Exclude
    @ColumnInfo(typeAffinity = ColumnInfo.BLOB)
    public byte[] thumbnail;
    @Exclude
    public boolean downloaded;
    @Exclude
    public boolean seen;
    @Exclude
    public boolean liked;
    @Exclude
    public boolean disliked;
    @Exclude
    public String path;     // Local attachment path

    @Exclude
    public String localFilePath; //Local attachment file path

    public String title;
    public String body;
    public String type;
    public String image;
    public String file;
    public String audio;
    public String video;


}

Solution

  • you have to change your Entity class like this

    In Java

    @Entity(tableName = "chat_message_table", indices = @Index(value = {"messageId"}, unique = true))
    public class Message {
    ...
    }
    

    In Kotlin

    @Entity(tableName = "chat_message_table", indices = [Index(value = ["messageId"], unique = true)])
    data class Message(@ColumnInfo(name = "messageId") val messageId: String) {
     @PrimaryKey(autoGenerate = true)
     var _Id: Int = 0
     ...
     }