8

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;


}
Ravi Rajput
  • 539
  • 4
  • 12

2 Answers2

20

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
 ...
 }
KuLdip PaTel
  • 1,069
  • 7
  • 19
  • weird but after changing the initial value for my primary key from `null` to `1` it works. No more same values in the field. – oyeraghib Nov 12 '22 at 11:23
  • @oyeraghib check here why you need to use 0 instead of 1 as primary key. https://stackoverflow.com/q/44109700/7229971 – KuLdip PaTel Nov 12 '22 at 13:59
1

Each time you save a model, you need to search database for if it exists. The search condition(s) should be remarkable, which can locate unique message. Here you can use messageId as search condition. If it exists, update it. If not, create new message and insert it.

Bejond
  • 1,188
  • 1
  • 11
  • 18