Figen Güngör
Figen Güngör

Reputation: 12559

Updating Realm Data When Version Changed

I have two language arrays in my arrays.xml. All languages and default languages.

I have a Language class which has two fields. Name and isSelected.

I am adding all languages to my Realm database on First run of my app. I am setting isSelected field of language if the language is in default languages array.

My question is when I update the all languages in my arrays.xml and publish an update for my app, how can I get the old realm data for selected languages and then clear the realm db and create a brand new with all languages in my arrays.xml and set the isSelected with the old realm data for selected languages?

Upvotes: 0

Views: 336

Answers (1)

Viraj Tank
Viraj Tank

Reputation: 1285

  1. If you just want to update existing language data and add non exciting language data, then you can use,

realm.executeTransaction(realm1 -> realm1.copyToRealmOrUpdate(languageList));

  1. If you want to delete all language data before adding the updated one as a fresh copy, then you can first delete all language data and add new list like this,

realm.executeTransaction(realm1 -> realm1.delete(LanguageClass.class)); realm.executeTransaction(realm1 -> realm1.copyToRealmOrUpdate(languageList));

  1. In case you want to delete entire Realm database file first before adding the new data, you can first delete the entire Realm, which will delete LanguageClass data and any other Realm class you may have, like this,

Realm.deleteRealm(realmConfiguration); realm.executeTransaction(realm1 -> realm1.copyToRealmOrUpdate(languageList));

NOTE: The most recommended option in your case would option no.1, which is the most safe and reliable way to update data in Realm.

NOTE2: Instead of copying language data every time, you should only copy/update language data when there is a change in the language data.

Upvotes: 1

Related Questions