How to convert RealmResults object to RealmList? - android

I have a RealmResults <Student> object. I want to convert it to RealmList <Student> object. any suggestions?

RealmList <Student> results = new RealmList<Student>();
results.addAll(realmResultList.subList(0, realmResultList.size()));

Please try and let me know if this work for you.
RealmList <Student> finalList = new RealmList<Student>();
finalList.addAll(yourRealmResults.subList(0, yourRealmResults.size()));

Since 0.87.0
Added Realm.copyFromRealm() for creating detached copies of Realm objects (#931).
Which allow just return list List<E extends RealmObject>

RealmResults implements the List interface and so does the RealmList.
RealmList <Student> results = new RealmList<Student>();
results.addAll(realmResultsList);

In new update you can use copyFromRealm method to do so :
RealmList<Student> finalList = realm.copyFromRealm(resultsAnswers);

RealmResults is returned if a query is expected to give a collection of objects (e.g. RealmQuery<E>.findAll()). Otherwise, single object queries will return a RealmObject.
Managed and Unmanaged Objects
RealmResults are managed objects, meaning they cannot be manipulated outside of Realm transactions and are confined in the thread that created them. Converting RealmResults into a RealmList will make the data unmanaged, as what #epicpandaforce pointed out, meaning the objects in the list are not connected to the database anymore and are basically normal Java objects which can be transferred in between threads and manipulated.
To convert RealmResults to a RealmList:
RealmResults<User> results = realm.where(User.class).findAll();
RealmList<Users> users = realm.copyFromRealm(results);
Changes to an unmanaged object will not in any means affect the original in the database unless a realm.copyToRealm(users), doing the opposite of copyFromRealm(), is executed after. Keep in mind that RealmLists can be managed or unmanaged, as a RealmObject from a RealmResult can have the following structure in which the RealmList in this case is a managed object:
class User {
int id;
String name;
RealmList<String> petNames;
}
Finally, copyFromRealm() returns a List so it's also possible to do
ArrayList<User> users = realm.copyFromRealm(results);

Realm has some new features check-in documentation
Realm Documentation
Realm has copyfromRealm function which we can use to convert the result to list
RealmList<Student> student=realm.copyfromRealm(Realmresult);

#JemshitIskenderov This should copy for you.
public RealmList<Student> convertResultToList(RealmResult<Student> realResultsList){
RealmList <Student> results = new RealmList<Student>();
for(Student student : realResultsList){
results.add(copy(student));
}
}
private Student copy(Student student){
Student o = new Student();
o.setCreated(student.getCreated());
o.setModified(student.getModified());
o.setDeleted(student.getDeleted());
o.setName(student.getName());
//List more properties here
return o;
}

Code:
public class RealmCollectionHelper {
public static <C extends RealmModel> RealmList<C> mapperCollectionToRealmList(Collection<C> objects){
if (objects == null){
return null;
}
RealmList<C> realmList = new RealmList<>();
realmList.addAll(objects);
return realmList;
}
}
Here my gist: https://gist.github.com/jmperezra/9b4708051eaa2686c83ebf76066071ff

Just another way of doing it:
RealmList<YourClass> dummy = new RealmList<>();
Iterator<YourClass> it = realmResultsList.listIterator();
while (it.hasNext()) {
dummy.add(it.next());
}

Related

Android: Convert LiveData ArrayList to Gson and back again

For my application, I have a recycler view that I'm using LiveData to populate. Each item in the recycler view is an Event object that I created. I'm using Room and Dao to store these Events and to create that abstraction layer between SQL and the repository and UI controller, but the problem is that Dao can only serialize primitize types into JSONs. I created type converters to convert between ArrayList and json, but I need to be able to convert between LiveData[ArrayList[Event]] in order to get this to work.
So far, this is what I have:
#TypeConverter
public static String fromEvent(LiveData<ArrayList<Event>> events){
Gson gson = new Gson();
String json = gson.toJson(events);
return json;
}
#TypeConverter
public static LiveData<ArrayList<Event>> fromEventString (String value){
Type eventType = new TypeToken<LiveData<ArrayList<Event>>>() {}.getType();
return new Gson().fromJson(value, eventType);
}
How do I interconvert between these two data types using Google's Gson library? Lol I'm obviously not too experienced with this.
Thanks for any help!!
This isn't exactly an answer, but I switched from ArrayList to the generic List, and it worked seamlessly. I was reading something about how Gson looks to the superclass of whatever data structure you're using to learn how to serialize and deserialize, so I wondered if switching to: List[Event] list = new ArrayList() instead of ArrayList[Event] list = new ArrayList() would do the trick. Indeed, for some reason RoomDatabase knew perfectly how to serialize it this way.

Realm for Android – RealmResult.sort() doing string based sorting?

In my application I am querying some data from realm about below model class.
After then I am sorting resulting data using realmResults.sort("point").
but result is not as expected.
Model class
public class FreeItem extends RealmObject {
private int itemId;
private int point;
private int freeQty;
private int freeItemId;
// geters setters
}
Querying code
if(realm==null||realm.isClosed()){
realm = Realm.getInstance(config);
}
PromotionPlan plan = realm.where(PromotionPlan.class).equalTo("id", planId).findFirst();
if(plan!=null) {
RealmResults<QtyDiscount> realmResults = plan.getDiscounts().where().equalTo("itemId", productId).findAll();
realmResults.sort("point");
return realmResults.subList(0,realmResults.size());
}
return new ArrayList<>();
Before sort( debug values)
FreeItem = [{itemId:61},{point:12},{freeQty:1},{freeItemId:61}]
FreeItem = [{itemId:61},{point:120},{freeQty:16},{freeItemId:61}]
FreeItem = [{itemId:61},{point:24},{freeQty:3},{freeItemId:61}]
FreeItem = [{itemId:61},{point:60},{freeQty:8},{freeItemId:61}]
After sort it is same as before.
So i tried to write own sorting process using below code, but it generates an exception and saying, since they are realm objects cannot replace.
Any help?
Sorting code
List<FreeItem> result = realmResults.subList(0, realmResults.size());
Collections.sort(result, new Comparator<FreeItem>() {
#Override
public int compare(FreeItem lhs, FreeItem rhs) {
if(lhs.getPoint()>rhs.getPoint())return 1;
if(lhs.getPoint()<rhs.getPoint())return -1;
return 0;
}
});
Exception
java.lang.UnsupportedOperationException: Replacing and element is not supported.
at io.realm.RealmResults$RealmResultsListIterator.set(RealmResults.java:826)
at io.realm.RealmResults$RealmResultsListIterator.set(RealmResults.java:757)
at java.util.AbstractList$SubAbstractList$SubAbstractListIterator.set(AbstractList.java:232)
at java.util.Collections.sort(Collections.java:1888)
Instead of using findAll() method you can use findAllSorted() and you can also give ASCENDING or DESCENDING order.
From Realm documentation:
findAllSorted(java.lang.String[] fieldNames, Sort[] sortOrders)
Finds all objects that fulfill the query conditions and sorted by
specific field names.
Parameters:
fieldNames - an array of field names to sort by.
sortOrders - how to sort the field names.
Returns: a RealmResults containing objects. If no objects match the condition, a list with zero objects is returned.
You have to use
plan.getDiscounts().where().equalTo("itemId", productId).findAllSorted("point",Sort.DESCENDING);
instead of
plan.getDiscounts().where().equalTo("itemId", productId).findAll();
realmResults.sort("point");
I hope it works for you.
This is the Updated version.. you can try
RealmResults<Notification_History>notification_histories=realm.where(Notification_History.class).findAll().sort("notification_count");

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 ?
Simplest to convert into java ArrayList:
ArrayList<People> list = new ArrayList(mRealm.where(People.class).findAll());
List<ArticleList> unmanagedList = realm.copyFromRealm(results);
Will do it.
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.
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.

Android Realm - Primary Key Constraint Exception & Duplication

I'm new to Android programming and Realm. Couldn't find any related articles so I'm posting the question here..
I'm writing to Realm from my JSONfile, which is recorded and reflected in the RealmBrowser. But when I restart my app, I'm getting error on io.realm.exceptions.RealmPrimaryKeyConstraintException: Value already exists: 20151101. All values are derived directly from my JSON file and I run it in a for loop under all data has been recorded in the Realm database.
for (int i = 0; i < jsonFile.length(); i++) {
try {
RealmConfiguration objectDB = new RealmConfiguration.Builder(getContext()).
name("objectDB.realm").build();
Realm realm = Realm.getInstance(objectDB);
realm.beginTransaction();
Object object = realm.createOrUpdateObjectFromJson(Object.class, jsonFile);
object.setPrimaryId(primaryId);
//and set more more data...
realm.copyToRealmOrUpdate(object);
realm.commitTransaction();
} catch (JSONException e) {
e.printStackTrace();
}
}
My understanding is that if the primaryKey exists on the Realm table, it will only update changes to any of the setters(), but now I'm having "io.realm.internal.Table.throwDuplicatePrimaryKeyException" error. Can anyone advise where or what I have done wrong along the way?
Many thanks to the kind folks here!
I think you should replace this
Object object = realm.createOrUpdateObjectFromJson(Object.class, jsonFile);
object.setPrimaryId(primaryId);
//and set more more data...
realm.copyToRealmOrUpdate(object);
With something like this
Object object = gson.fromJson(jsonFile, Object.class);
object.setPrimaryId(primaryId);
realm.beginTransaction();
realm.copyToRealmOrUpdate(object);
realm.commitTransaction();
Gson is a dependency of Realm, so I think you can just do Gson gson = new Gson() somewhere to make one.
Why do you have this line?
object.setPrimaryId(primaryId);
I would assume that information would be part of the jsonFile, and the primary key you set there probably conflicts with one that already exists.

How to retrieve data from ArrayList<ModelObject> not from ArrayList<String>?

Hi I'm still new to java data management.
I have a model object class named Computer which has 3 fields: processor, ram, hddSize.
I created a ArrayList
ArrayList<Computer> myCompList = new ArrayList<Computer>();
Computer comp1 = new Computer();
comp1.setProcessor("1.5 GHZ");
comp1.setRam("512 MB");
comp1.setHddSize("100 GB");
Computer comp2 = new Computer();
comp2.setProcessor("2.5 GHZ");
comp2.setRam("512 MB");
comp2.setHddSize("50 GB");
myCompList.add(comp1);
myCompList.add(comp2);
Now How can I retrieve data at index1 of the ArrayList above?
PS: I know how to do it if its a ArrayList< String> by convert it to String[] and then String[index].
Look at the Javadocs for ArrayList
This is where you should check for simple questions like this. The answer can be found in the "Method Summary" section.
Assuming that you have created getters and setters in your Computer class:
String processor = myCompList.get(1).getProcessor();
String ram = myCompList.get(1).getRam();
String hddSize = myCompList.get(1).getHddSize();
Can't you just go myCompList.get(0); ?
An arraylist of objects is essentially the same as an arraylist of strings. The .get() method returns the specific object at the given index. Here is the documentation for ArrayList.
myCompList.get(index) will return you data on the given index, make sure index number wouldn't be greater than array size, it will give you index out of bounds exception.

Categories

Resources