How to save java list in android realm database

How can we save java list in android database. I try to save it using the setter method present in my model, but it does not work, and I get: "Each element of" value "must be a valid managed object" in the exception message.

public void storeNewsList(String categoryId, List<News> newsList) { Realm realm = Realm.getDefaultInstance(); realm.beginTransaction(); NewsList newsListObj = realm.createObject(NewsList.class); newsListObj.setNewsList(new RealmList<>(newsList.toArray(new News[newsList.size()]))); newsListObj.setCategoryId(categoryId); realm.commitTransaction(); realm.close(); } 
+5
source share
2 answers

Replace code

 public void storeNewsList(String categoryId, List<News> newsList) { try(Realm realm = Realm.getDefaultInstance()) { realm.executeTransaction(new Realm.Transaction() { @Override public void execute(Realm realm) { NewsList newsListObj = new NewsList(); // <-- create unmanaged RealmList<News> _newsList = new RealmList<>(); _newsList.addAll(newsList); newsListObj.setNewsList(_newsList); newsListObj.setCategoryId(categoryId); realm.insert(newsListObj); // <-- insert unmanaged to Realm } }); } } 
+6
source

If you use @PrimaryKey then insertOrUpdate will do the trick

 try(Realm realm = Realm.getDefaultInstance()) { realm.executeTransaction(new Realm.Transaction() { @Override public void execute(Realm realm) { RealmList<News> _newsList = new RealmList<>(); _newsList.addAll(myCustomArrayList); realm.insertOrUpdate(_newsList); // <-- insert unmanaged to Realm } }); } 
0
source

All Articles