No Name
No Name

Reputation: 783

How to correctly write data in Realm?

I have a method in which I write data in Realm:

public void setChatsList(final ChatsModel chatsModel) {
    Realm realm = null;

    try {
        realm = Realm.getDefaultInstance();

        realm.executeTransaction(new Realm.Transaction() {
            @Override
            public void execute(Realm realm) {
                realm.copyToRealmOrUpdate(chatsModel);
            }
        });

    } finally {
        if (realm != null) {
            realm.close();
        }
    }
}

And I read the data from the database in this method:

ChatsModel getAllChatsList() {
    Realm realm = Realm.getDefaultInstance();
    RealmResults<ChatsModel> chatsModelResult = realm.where(ChatsModel.class).findAll();

    ChatsModel chatsModel = chatsModelResult.get(0);

    return chatsModel;
}

When I use the copyToRealmOrUpdate() method to write to the database, it does not save. That is, when you get data in the method, getAllChatsList() returns 0.

And when I write using the insertOrUpdate() method, each time it writes, it does not update an existing record but writes it next to the previous one even if they have the same data

Why the number of entries increases. Although the same object. Well, if there was a list, but I have only one object and to get the last record I do this:

ChatsModel chatsModel = chatsModelResult.get(chatsModelResult.size() - 1);

Why? Can not I just read without sending an argument - chatsModelResult.size() - 1?

Question: How can I solve the problem of writing and reading?

Upvotes: 0

Views: 439

Answers (1)

EpicPandaForce
EpicPandaForce

Reputation: 81539

ChatsModel getAllChatsList() {
    Realm realm = Realm.getDefaultInstance(); // <-- realm instance never closed
    RealmResults<ChatsModel> chatsModelResult = realm.where(ChatsModel.class).findAll();

    ChatsModel chatsModel = chatsModelResult.get(0);

    return chatsModel;
}

By opening unclosed Realm instances, on non-looper background threads, your version will be retained on an older version of Realm and won't be able to update itself.

A possibility would be proper lifecycle management, or calling realm.refresh().

Upvotes: 1

Related Questions