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;
}
Note − Use the INSERT IGNORE command rather than the INSERT command. If a record doesn't duplicate an existing record, then MySQL inserts it as usual. If the record is a duplicate, then the IGNORE keyword tells MySQL to discard it silently without generating an error.
Possible causes can be operational (e.g. a salesperson registered the same customer multiple times), technical (e.g. an IT bug led to customer accounts being created twice) or related to data manipulations (e.g. an intermediary data table is built in such a way that there are duplicate rows).
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
...
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With