ChatRoom:
public class ChatRoom extends RealmObject{
#PrimaryKey
int chatRoomID;
RealmList<ChatMessage> chatMessages;
//getters & setters ...
}
Message class:
public class ChatMessage extends RealmObject {
int chatMessageID;
String chatMessageContent;
User author;
//getters & setters ...
}
User:
public class User extends RealmObject {
#PrimaryKey
int Id;
String Name;
//getters & setters ...
}
Well the first time that the chatmessage is created is fine but in the second time I get an error: Value already exists: 5 [Id of the User]
How can I update the user object when is added to my chatmessage list instead of created a new one?
This is the way that I add a new chatMessage:
mRealm.beginTransaction();
ChatRoom chatRoom = mRealm.where(ChatRoom.class).equalTo("chatRoomID", chatRoomID)
.findFirst();
chatRoom.getChatMessages().add(chatMessage); // add to the list
mRealm.commitTransaction();
It is because of chatMessage is a unmanaged RealmObject and it has the same primary key with one is saved by Realm already.
So if an object is unmanaged object, when added it to a managed RealmList, Realm will try to create it. And an exception will be thrown when an object with the same pk already exists.
To solve this, use copyToRealmOrUpdate() to get a managed RealmObject first then add it, like:
ChatMessage ch = new ChatMessage();
ch.SetChatMessageID(someId);
ch.setChatMessageContent("text");
ch.setChatMessageAuthor(author);
mRealm.beginTransaction();
ch = mRealm.copyToRealmOrUpdate(ch); // get/create a managed RealmObject
ChatRoom chatRoom = mRealm.where(ChatRoom.class).equalTo("chatRoomID", chatRoomID)
.findFirst();
chatRoom.getChatMessages().add(ch); // add to the list
mRealm.commitTransaction();
Related
Items upon inserting
Items upon retrieving
So here is the thing:
I have an Object Product which extends RealmObject.
Inside the Product object, there is an attribute: RealmList. Bundle also extends RealmObject.
Inside the Bundle Object, there is an attribute: RealmList. ProductBundle extends RealmObject.
Now all those lists are not empty nor null by the time they should be inserted.
After insertion, if I query Realm for a list of Products, I will receive a list that has a list of RealmList. However, inside each of the Bundle items, the RealmList< ProductBundle> productBundles is always empty.
class Product extends RealmObject{
RealmList<Bundle> bundles= new RealmList<Bundle>();
boolean isLocallyAddedToCart;
}
class Bundle extends RealmObject{
RealmList<ProductBundle> productsBundles = new RealmList<ProductBundle>();
}
class ProductBundle extends RealmObject{
String title;
}
Any thoughts on that??
Query:
RealmResults<Product> cartItem = realm.where(Product.class).equalTo("isLocallyAddedToCart", true).findAll();
Inserting:
public void insertAddToCart(#NonNull ArrayList<Product> items) {
try {
Realm realm = getRealmInstance();
realm.beginTransaction();
realm.insertOrUpdate(items);
realm.commitTransaction();
realm.close();
} catch (Exception ex) {
ex.getStackTrace();
}
}
Handling the objects:
RealmList<BundleProductOption> bundleProductOptions = new RealmList<>();
private SparseArray<List<ProductBundle>> optionsFinalSelection = new SparseArray<>();
BundleProductOption bundleProduct = new BundleProductOption();
bundleProduct.setDefaultTitle(bundleProductOption.getDefaultTitle());
bundleProduct.setOptionId(bundleProductOption.getOptionId());
bundleProduct.setParentId(bundleProductOption.getParentId());
bundleProduct.setRequired(bundleProductOption.getRequired());
bundleProduct.setType(bundleProductOption.getType());
RealmList<ProductBundle> productBundles = new RealmList<>();
productBundles.addAll(optionsFinalSelection.get(i));
bundleProduct.setProductsBundle(productBundles);
product.setSelectedOptions(bundleProductOptions);
you must manage your insertion with ID as a primary key in each model.
when u insert or update u must use a primary key for saving all states of your data, and then u can do not use them, but realm need them for arrange insert or update method.
keep me updated with your issue .
I have two classes:
public class Employee extends RealmObject {
#PrimaryKey
long id;
String name
Department department;
//getters setters etc.
}
public class Department extends RealmObject {
#PrimaryKey
int id;
String name;
//getters setters etc.
}
It is one to many relationship. One department can have multiple employees. I've tried to make some queries.
realm.where(Employee.class).equalTo("department.name", "deptName").findAll()
realm.where(Department.class).equalTo("employee.name", "empName").findAll()
The first one is working, the second one has an error:
Invalid query: employee does not refer to a class.
How to make the second one work? Do I must make a RealmList of Employees in Department class?
I wanted in this query fetch all Departments which have an Employee with specified name.
Realm 3.5.0+:
public class Employee extends RealmObject {
#PrimaryKey
long id;
String name
Department department;
//getters setters etc.
}
public class Department extends RealmObject {
#PrimaryKey
int id;
String name;
#LinkingObjects("department")
private final RealmResults<Employee> employees = null;
//getters setters etc.
}
realm.where(Employee.class).equalTo("department.name", "deptName").findAll()
realm.where(Department.class).equalTo("employees.name", "empName").findAll()
I have two tables (Dog & Person) defined in Realm object and need use 1:n relation.
My Person class is:
public class Person extends RealmObject {
#PrimaryKey
private int id;
private int age;
private Dog dog;
/** Getters & setters **/
}
My Dog class is:
public class Dog extends RealmObject {
#PrimaryKey
public int id;
public String name;
/** Getters & setters **/
}
When the table "Dogs" contains data loading from internet. I need add dog id to my Person table as relationship, when save object Person. If save to "Person" table dogId, than i dont join data. I need select data from Person include dog name.
Is possible in realm as relationship? Or I use another realm query, where i will search by dog where id?
Thank you for response.
Let's say I have a structure of realm-objects that looks like this -
public class Person extends RealmObject {
#PrimaryKey
private int id;
private String name;
private List<Pet> pets
// Setters, getters...
}
public class Pet extends RealmObject {
private String name;
private MedicalRecord record;
// Setters, getters...
}
public class MedicalRecord extends RealmObject {
private String something;
private String somethingElse;
// Setters, getters...
}
Now I received a new Person object with an existing id (primary-key) and I want to update this person.
So I do something like this -
realm.beginTransaction();
realm.copyToRealmOrUpdate(person);
realm.commitTransaction();
The trouble is that this person's pet list (and the pets' medical records), are still out there in the db. not linked anymore to this person, but still there.
I tried to do this -
Person existingPerson = realm.where(Person .class).equalTo("id", ID).findFirst();
existingPerson.getPets().clear();
But no success there. How can I remove subobjects of realmObjects?
Also, is there a way to define a policy for a realm-object so that it will remove itself once there is no reference to it (it's not linked to any parent-object)?
Now you can, and method was renamed from last commit to realmList.deleteAllFromRealm()
there is a problem when I use the Realm in Android.
I wrote two RealmObject.
public class Feed extends RealmObject {
#PrimaryKey
private long id;
private String content;
private long uid;
...
}
public class User extends RealmObject {
#PrimaryKey
private long uid;
private String name;
...
}
I want to search the result with:
[feed_id, feed_content, user_id, user_name ...]
should I need add a new Object ( FeedUser extends RealmObject) with these fields? Is this waste the memory?
Also I want to listen the change about user Object, if I add the FeedUser, when User changed. How to update FeedUser synchronous ?
thx :)
Take a look at how Relationships work in Realm.
If a user can have multiple Feed objects then you can have List<Feed> in your User object instead of defining user id yourself in your Feed. It will be something like this. You can read documentation more to see how you will get User with its feed in one query.
public class Feed extends RealmObject {
#PrimaryKey
private long id;
private String content;
...
}
public class User extends RealmObject {
#PrimaryKey
private long uid;
private String name;
private RealmList<Feed> feeds;
...
}