NyanNyan
NyanNyan

Reputation: 49

How to save data in realm database

How to save data in the Realm database? I tried to write the code below. Example: I have a list of size 4. In the for loop, I can view all the data from this list and after I do this method - copyToRealmOrUpdate.

So, if I want to check the size of my database, I see the size of only 1 but not 4.

More interesting is that I used this code in another class, and it works fine. What is the problem? I disabled the migration, rewrote the code, but I still don't know what else can be done.

try {
            realm = Realm.getDefaultInstance();
            if (entityList.size() > 0) {
                realm.executeTransaction(r -> {
                    Log.d(LOGS, "SIze Entity list: " + entityList.size());
                    for (int i = 0; i < entityList.size(); i++) {
                        DbRealm db = new DbRealm();
                        db.setFromEntity(entityList.get(i));
                        Log.d(LOGS, "entityList.get(i): " + entityList.get(i));
                        Log.d(LOGS, "File: " + entityList.get(i).getFiles());
                        Log.d(LOGS, "Comment: " + entityList.get(i).getComment());
                        Log.d(LOGS, "Date: " + entityList.get(i).getDate());
                        r.copyToRealmOrUpdate(db);
                    }
                });
                Log.d(LOGS, "Check FindAll: " + String.valueOf(realm.where(DbRealm.class).findAll().size()));
            }
        } finally {
            if (realm != null) {
                realm.close();
            }
        }

Upvotes: 1

Views: 1596

Answers (1)

JaFer
JaFer

Reputation: 213

If you see the Realm documentation says the following:

Updates an existing RealmObject that is identified by the same PrimaryKey or create a new copy if no existing object could be found.

In your case the PrimaryKey is the same so the Realm update the data instead of create new one.

So I recommend you to create in your DbRealm object a PrimaryKey variable, for example, you can you use the "i" variable although I don't recommend you that but to try and see that it's is the solution you can use it.

Upvotes: 1

Related Questions