Alexey K
Alexey K

Reputation: 6723

Realm Android - How can I convert RealmResults to array of objects?

I have an object

public class ArticleList extends RealmObject {

@PrimaryKey
private String id;
private String title;
private String subtitle;
private String image;
private String category;

}

What I want to do is to fetch result from Realm and them convert result to ArticleList[]

Fetch I do by using

RealmResults<ArticleList> results = realm.where(ArticleList.class).equalTo("category", "CategoryName").findAll();

What do I have to do next to get an array of objects ?

Upvotes: 16

Views: 28016

Answers (4)

Aniket Kadam
Aniket Kadam

Reputation: 241

List<ArticleList> unmanagedList = realm.copyFromRealm(results);

Will do it.

Upvotes: 23

EpicPandaForce
EpicPandaForce

Reputation: 81588

Instead of trying to convert to an array, you should extend the abstract RealmBaseAdapter class from https://github.com/realm/realm-android-adapters to keep your results in sync.

Realm provides these classes as an example of how to create an auto-updating list with a RecyclerView or a ListView.

Upvotes: 2

Farhan
Farhan

Reputation: 3363

Simplest to convert into java ArrayList:

    ArrayList<People> list = new ArrayList(mRealm.where(People.class).findAll());

Upvotes: 28

Adam S
Adam S

Reputation: 16414

RealmResults has a toArray() method - also toArray(T[] contents) (note the RealmResults inheritance chain). You can use these as follows:

ArticleList[] resultArray = (ArticleList[]) results.toArray();

Or

ArticleList[] resultArray = results.toArray(new ArticleList[results.size()]);

Ideally, you'd want to use RealmResults instead. This allows you to get "free" updates to your data, as well as all the conveniences of a List.

Upvotes: 12

Related Questions