Using dynamic realm in android - android

Is there anyone used dynamic realm in android.I'm searching a lot in net but I cannot find any sample code using dynamic realm database, except this realm documentation in android
RealmConfiguration realmConfig = new RealmConfiguration.Builder(this).build();
DynamicRealm realm1 = DynamicRealm.getInstance(realmConfig);
// In a DynamicRealm all objects are DynamicRealmObjects
DynamicRealmObject person = realm1.createObject("Person");
// All fields are accessed using strings
String name = person.getString("name");
int age = person.getInt("age");
// An underlying schema still exists, so accessing a field that does not exist
// will throw an exception
person.getString("I don't exist");
// Queries still work normally
RealmResults<DynamicRealmObject> persons = realm1.where("Person")
.equalTo("name", "John")
.findAll();
but when I run this code I'm getting this error message.
The class class_Person doesn't exist in this Realm.
can anyone help me about this and show me a code sample?

A DynamicRealm does not automatically generate any schemas, so if you have a Person model class, you cannot access it dynamically before you opened a Realm normally using Realm.getInstance() (as that will create the schema). Otherwise you manually have to create the Person class using DynamicRealm.getSchema()

in order to create new instance of the existing schema in the realmDB 
you have to create an instance by calling realm method createObject inside realm method beginTransaction and commitTransaction like mentioned below.
realm.beginTransaction();
DynamicRealmObject person = realm.createObject("Person");
person.setString("name", "kiran");
person.setInt("age", 29);
realm.commitTransaction();
and the methods setString and setInt are the methods of the DynamicRealmObject.

Please go through the documentation https://realm.io/docs/java/latest/api/io/realm/DynamicRealm.html for more understanding of the DynamicRealms.

Related

realm with parceler to pass data across activities and services

I am using parceler with realm to pass data from activity to service.
i have few restrictions of realm and parceler
Restrictions
There are some important restrictions to be aware of when using Parceler:
If you model contains a RealmList you need to register a special adapter.
Once an object has been parcelled, it becomes detached from Realm and at this point behaves like an unmanaged object containing a snapshot of the data.Further changes to this object will not be persisted in Realm
for rule 1 i have register a special adapter for it , but for rule 2 i have a doub that at what point realm got deatched
is it at the time of annoting a class i.e. using
#Parcel(value = org.parceler.Parcel.Serialization.BEAN, analyze = { VisitInfo.class })
or at the time of unwrapping and wrapping
RequestInfo requestInfo = Parcels.unwrap(intent.getParcelableExtra("visitData"));
It becomes an unmanaged copy when you call Parcels.wrap() in the first place.
Realm by default expects you to send the primary key of the object over in the intent, and to requery it in the other Activity.

Android: how to keep realmlist updated in the UI

I have a recyclerview which shows a list of students.
All of the students are held in a realmlist in the adapter.
When the user can ask for a data refresh, than the server sends the list of students back to the user.
What i am doing now is to download all of the information from the server , store it in the db , than retrieving it from the database(via realmresults) and than converting the realmresult to realmlist.
My question is how to properly update the UI?
I have seen in the documentation that realmlist have a managed mode where they are updating the ui automatically..
What is this managed mode? What does it means?
How do i use the realmlist to keep it in a managed state?
And what is the right way(aka best practice) to use realmlists?
Note that i cannot hold my information as realmresult directly because im performing some manipulation on the data that i dont want it to be saved.
Managed Object vs. Standalone
The standalone RealmObject/RealmList is created through the Object's constructor or the Realm.copyFromRealm() method. The data accessing in the standalone object won't go through the underline storage engine, instead, it behaves just like normal object. So the standalone object won't be refreshed when data changes. Examples for standalone object:
MyModel myModel = new MyModel(); // Standalone
MyModel model = realm.where(MyModel.class).findFirst(); // This is managed object.
MyModel standaloneModel = realm.copyFromRealm(model); // The returned value is standalone object.
MyList myList = new MyList(); // Standalone
The managed RealmObject/RealmList are accessing data though Realm's underlying storage engine. They are created when you do query from Realm, or the return from the copyToRealm() (and its variant methods). Like:
MyModel model = realm.where(MyModel.class).findFirst();
MyModel model = new MyModel(); // This is a standalone object.
model = realm.copyToRealm(modle); // The returned value is managed by Realm now.
MyList myList = realm.where(MyModel.class).findFirst().getMyList();
How to properly update the UI
The suggestion is using Realm's change listeners. See https://realm.io/docs/java/latest/#notifications
And what is the right way(aka best practice) to use RealmList?
This is a bit confusing, but Realm is introducing RealmCollection into the next major release (v0.89.0). See https://github.com/realm/realm-java/pull/2345.
Note that i cannot hold my information as realmresult directly because im performing some manipulation on the data that i dont want it to be saved.
If the RealmList is in managed mode, the data changes will be saved as well. If you don't want some data to be saved, you could consider to use #Ignore annotation on those fields. See https://realm.io/docs/java/latest/#ignoring-properties
Update on 04072016
RealmList vs. RealmResults:
RealmList is a list of RealmObject saved as a field of a RealmObject. It represents the one-to-many relationship in Realm.
RealmResults is the results of query.
Both of them (if RealmList in managed-mode) will be auto-refreshed when data changes.
You can get a RealmResults from a RealmList by RealmList.where() like:
RealmResults results = myRealmList.where().findAll();
This answer will be a bit out-of-date after Realm v0.89.0 released, because of new RealmCollection.

How can I create a Realm database with initial data for my android app?

I am trying to create a database for my android application using Realm. I need to have data that is pre-populated when the app is installed. Setting a Realm Migration as part of the RealmConfiguration does not run when the version of the database is 0 (defaults to 0 initially). How can I add data the first time the application is setup?
Realm Java 0.89 introduced a method that allows for specifying a transaction to be run when a Realm database is created for the first time. This method, RealmConfiguration.Builder.initialData(Realm.Transaction transaction), is called as part of setting up the RealmConfiguration Builder.
For example
RealmConfiguration config = new RealmConfiguration.Builder(context)
.name("myrealm.realm")
.initialData(new MyInitialDataRealmTransaction()),
.build();
What I am doing right now that works is to check if this is the first time my app is installed and create a new object.
if (Preferences.freshInstall(getApplicationContext())) {
Realm realm = Realm.getDefaultInstance();
realm.beginTransaction();
Category inbox = new Category("Inbox", "#445566");
realm.copyToRealm(inbox);
realm.commitTransaction();
Preferences.notNew(getApplicationContext());
}
There should be a better way to do this using Realm Migrations
The initial data transaction setup, as shown by #Benjamin in Realm Java works! I only wish that it was present in Realm Cocoa, as well.
I've created an issue for this, in the Github tracker here, #3877.

Realm Find Queries Result in Empty Objects [duplicate]

This question already has answers here:
Cannot retrieve field values from realm object, values are null in debugger
(5 answers)
Closed 5 years ago.
When doing find queries for objects I'm getting "empty" objects (non-null, but not populated). However, in the debugger I can see the data for the object in the object description (see below). I've also verified the data is there using the Realm Browser. I've tried different find queries, querying with filter criteria, using the same Realm object for inserts/queries, using different Realm objects for inserts/queries, refreshing the Realm, etc.
If I Log fields in the RealmObject I see the proper data print out. However, I'm trying to convert these models into other models for use in RxJava per https://realm.io/news/using-realm-with-rxjava/.
Here's some sample code where reproduced the issue. Below that is a screenshot when breaking at verifyRealm.close().
RealmTester realmTester1 = new RealmTester();
realmTester1.setFirstName("Tester1");
realmTester1.setLastName("ABC");
RealmTester realmTester2 = new RealmTester();
realmTester2.setFirstName("Tester2");
realmTester2.setLastName("XYZ");
Realm insertRealm = Realm.getDefaultInstance();
insertRealm.refresh();
insertRealm.beginTransaction();
insertRealm.copyToRealm(realmTester1);
insertRealm.copyToRealm(realmTester2);
insertRealm.commitTransaction();
insertRealm.close();
Realm verifyRealm = Realm.getDefaultInstance();
RealmResults<RealmTester> verifyTesters = verifyRealm.where(RealmTester.class).findAll();
verifyRealm.close();
I have a screenshot of the debugger at: http://i.stack.imgur.com/1UdRr.png
I'm using v0.82.1. Any thoughts on why the models here aren't populating?
The idea behind realm-java is that we are generating Proxy class inherits from user's model class, and override the setters and getters there.
It is totally normal that you see null values for the model's field in the debugger, since the Realm are not setting them. (zero-copy, Realm is trying to reduce the memory usage by managing the data in the native code and sharing them whenever it is possible.)
Because of this, when you want to access a Realm model's field, please always use setters and getters. Checking the generated Proxy class will help you to understand this, it is quite simple actually. It is located in the build directory named like MyModelRealmProxy.java
And also check this section of the documents, it would give you some idea about the standalone object and how to write them to Realm.

Create standalone object from realm result in android

I am new to android realm.
I am using follwing code to get product object from realm.
ProductModel prodObj = realm.where(ProductModel.class).equalTo("product_id","12").findFirst();
How can i create standalone copy of prodObj?
I want to update some field's value that should not affect in realm database. I don't want to set it manually with setters method because model class contains too many fields. Is there any easy way to create standalone copy of prodObj?
Since 0.87.0
Added Realm.copyFromRealm() for creating detached copies of Realm objects (#931).
Realm only has a copyToRealm method and not a copyFromRealm method. Currently, there is a number of restriction to model classes (see https://realm.io/docs/java/latest/#objects) but we are investigating and experimenting how to lift these.
We have an open issue about exactly what you are asking: https://github.com/realm/realm-java/issues/931. But for the time being, you will have to copy our objects manually.
In case anyone wondered like me how we can implement this copyFromRealm(), this is how it works:
ProductModel prodObj = realm.where(ProductModel.class)
.equalTo("product_id", "12")
.findFirst();
ProductModel prodObjCopy = realm.copyFromRealm(prodObj);
You can serialize an object into a JSON string and deserialize into a standalone object by Jackson like:
ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(yourObject);
objectMapper.readValue(json, YourModel.class);
GSON might not work because it doesn't support getter/setter when it makes a JSON.
I know it's a horrible solution.
But it might be the only way yet.

Categories

Resources