Began his acquaintance with Realm. Created a simple table:

public class NoteModel extends RealmObject { private String note; private String header; private Date date; /* геттеры и сеттеры для данных * ... */ } 

And learned how to fill it with data. I deduce the data by means of RecyclerView in CardView elements. Now I want to select CardView and change the data of this record. How do I find exactly the record? In SQLite there is an id field and it is unique for each record, but in Realm there is no such thing. Should I determine the id field in the model myself? The only information that I found in the docks / English-speaking forums is that you can use to update the information.

 copyToRealmOrUpdate(obj); 

or

 insertOrUpdate(obj); 

but I do not quite understand how I can change a specific entry with their help.

I will be glad to any help / examples with code / projects from the gita.

  • for this to work, you need to define a field in the model with the @PrimaryKey annotation; the method will orient itself by the value of this field — update an existing record or create a new one (if a record with that key value has not yet been created). Another problem follows from this: Realm does not have an auto-increment key and you will have to write your own method to generate it and ensure uniqueness, which is sad (though there are already several implementations on the network) - pavlofff
  • in the documentation about this is quite clearly stated , similarly, see the second method. Which one to use is also not an unequivocal question - pavlofff
  • public void execute (Realm bgRealm) {Number currentId = bgRealm.where (NoteModel.class) .max ("id"); if (currentId! = null) {currentId = currentId.intValue () + 1; } else {currentId = 0; } NoteModel noteModel = bgRealm.createObject (NoteModel.class); noteModel.setID (currentId.intValue ()); noteModel.setHeader (header); noteModel.setNote (note); noteModel.setDate (date); } like this? - Evgeny Vasilyev
  • one
    The method for obtaining the id is best to put in a separate static class, such as Utils or as a successor to Application - pavlofff

1 answer 1

Suppose we have one model:

 note = "note1"; header = "header1"; date = ...; 

For example, we want to change the header field of the model whose note field is "note1":

 NoteModel noteModel = Realm.getDefaultInstance().where(NoteModel.class).equalTo("note", "note1").findFirst(); noteModel.setHeader("header2"); 

In theory, it should work as I remember. But better see of.doku . There are examples above the roof.

PS I forgot to add that the need to complain in transactions. I think you know this very well how to do it :)