Alexey K Alexey K - 2 months ago 37
Android Question

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 ?

Answer

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.

Comments