Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to store java list in realm android database

How we can store java list in realm android database. I try to store it by using setter method present in my model, but it doesn't work and I get "Each element of 'value' must be a valid managed object" in 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(); 
} 
like image 658
Anil Avatar asked May 02 '17 12:05

Anil


People also ask

Where is realm database stored android?

You can find your realm file in the Device File Explorer tab at the bottom right of Android Studio. The location will be /data/data/com.


1 Answers

Replace code with

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
             }
        }); 
    }
} 
like image 152
EpicPandaForce Avatar answered Oct 12 '22 17:10

EpicPandaForce