If I call write and update an object with a list of newly created other objects, will those objects automatically be written into Realm as well?
If I understand your question correctly, you will update a Realm Object inside a write transaction and that object has a one-to-many relationship to another Realm Object. Your class may look like this for example:
public class Owner: Object {
let listOfObjects: List<SomeObject> = List<SomeObject>()
}
Then if you create a list of type SomeObject in a write block and set your class' listOfObjects to the newly created list, the new list of objects will be persisted in Realm when the write block ends. (Assuming your SomeObject class is a subclass of Object ofcourse)
From my understanding (in Realm Objective-C and Realm Swift at least), no. If you create a new list of objects that aren't persisted in Realm yet and assign them as child objects of an object that is, they still won't be guaranteed to be added to Realm that way.
For best practice, I recommend that in your write transaction, you both explicitly add the new objects to Realm and then add them to the child object list of that object.
Related
I am building an WPF application using the MVVM Light Toolkit and specifically SimpleIoc.
I have a parent viewmodel that dynamically creates child viewmodels. When doing this I am using "standard" dependency injection to pass a IConfigService as a parameter to the constructor. I want the IConfigService to be a unique instance for each child viewmodel. So I try this:
IConfigService service = SimpleIoc.Default.GetInstance<IConfigService>(key);
ChildViewModel vm = new ChildViewModel(service);
Where key is a unique identifier for each child viewmodel. According to the documentation of MVVM Light and SimpleIoc this GetInstance method:
...provides a way to get an instance of a given type corresponding to a given key. If no instance had been instantiated with this key before, a new instance will be created.
There is also a remark that the class must have been registered before, else it returns null. In my case it has been, in ViewModelLocator:
var configService = new ConfigService();
SimpleIoc.Default.Register<IConfigService>(() => configService);
However, the GetInstance call returns the same instance every time.
What am I doing wrong here?
You registered an already instantiated object.
SimpleIoc does not create its own instances with this overload. It always returns configService. Either you need to perform the instantiation within the lambda, because you are using a factory overload, or you can do this more easily by just passing the ConfigService type. SimpleIoc will take care of the instantiation itself.
In Short
I seem to have landed on a MAJOR anti-pattern of saving objects WAY too many times. I've read through the limited Objectify docs and can't seem to find the right pattern to use.
Details
I have multiple objects I want to store. They are all transient (they don't exist in the database yet) and they have a one-to-many relationship. I don't want to sit and call ofy().save() on every last object in my hierarchy.
In the following example, a Player has a List of Cards.
My Model:
#Entity
public class Player {
#Id private Long id = null;//will be generated
private List<Ref<Card>> cards = new ArrayList<Ref<Card>>();
//getters and setters here
}
public class Card{
#Id private Long id = null;//will be generated
//lots of other fields and getters and setters here
}
My Operation:
I need to create a new player and new card, with the player having a reference to the card in his List "cards."
IDEAL SOLUTION:
I would like to just create the player and card java objects, set their relationships, and pass them to Objectify to be saved. Like this:
Player player = new Player();
Card card = new Card();
player.setPlayer(Ref.create(card));
ofy.save().entity(player).now();
That will fail. The 3rd line attempts to create a new Ref for Card, which cannot be done because Card doesn't have an Id yet, which will be assigned to it once it's already persisted. It seems I must never associate an object with another until one has already been saved.
Current Crappy Solution
So, my solution must be to save the Card first, and then relate it to the Player, then save the player.
Player player = new Player();
Card card = new Card();
ofy().save().entity(card).now();
player.setPlayer(Ref.create(card));
ofy().save().entity(card).now();
This is insane. It seems reasonable at first, but my app is dealing with many more relationships than just this, and with this pattern my algorithm will be a spiderweb of checking for transient objects inside collections before saving the entity I'm actually concerned with.
There MUST be some way to tell Objectify to just SAVE all child/related entities along with the entity I've requested, and furthermore generate the Ids necessary instead of throwing an Exception at me.
Furthermore, I'll also need this sort of "recursive save" solution even when none of my objects are transient (ie they all have IDs already). I can't waste my time iterating through collections and then all the collections WITHIN those collections and saving them all. I'm going to need some way of telling Objectify to just SAVE THIS WHOLE HEIRARCHY OF OBJECTS I just passed you.
I've been reading around this #Load annotation and I feel like maybe there's something in there I'm missing... I don't know. Need help. Documentation is slim.
UPDATED SOLUTION
For posterity -
Using the allocateId() method decouples the entire ID generation constraint away from the database and you get a VERY clean pattern, particularly if you do as I did:
All database #Entity classes get a private constructor and a static public factory for creating transient objects. This static factory method ( createTransient() ) will always allocate a new ID. So then, all client code can use this method for acquiring new transient objects, or the obvious objectify load for acquiring existing persisted instances. Simple. Done. Lovely.
I recommend two things:
Allocate ids manually when you construct your objects using ObjectifyFactory.allocateId(). Do not use the "save with null autogenerates" feature. As you've noticed, it's a PITA to deal with entity objects that have null ids, so don't allow them to exist.
Use deferred saves. ofy().defer().save().entity(blah); You can save almost any number of things this way and they'll only get saved once on commit (or closing of the objectify session). Deferring save on the same entity multiple times produces only a single save.
This pattern of leaving ids null and filling it in on save is a holdover from the JPA days. It didn't work very well with JPA either; there were plenty of frustrating edge cases dealing with entities missing ids (especially when you wanted to put the in maps or sets). The best solution is to simply guarantee that no entity is ever missing an id in the first place.
Note that you'll want to allocate the id in a custom constructor, not the no-args constructor that Objectify uses to build your entity on load. Allocating an id is cheap but still a call to the GAE service layer and you don't want to do this on every load.
I am creating some hack kind of thing in existing android code to verify database creation and its accessibility across layers in application.
For this I have modified an existing function of .java file but I am facing an issue while calling constructor of SQLiteOpenHelper.
The signature is SQLiteOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version)
And I don't know how to create this Context instance. From googling I am seeing it is being some kind of activity class instance.
What ways are there to create this Context instance? Do we have to have activity class implemented?
Have a look at this question. It shows how to obtain a reference to the current Context object statically.
The gist of it is that you have to store a reference to the context that can be accessed statically from other sections of code.
P.S. You can't really "create" a context. That is something that is provided to you by the Android platform.
Just call:
this.getApplicationContext()
from wherever you are trying to create the instance of SQLiteOpenHelper.
Basically I want to make my script service only serialise properties that are not null on an array of object I am returning... So this..
{"k":"9wjH38dKw823","s":10,"f":null,"l":null,"j":null,"p":null,"z":null,"i":null,"c":null,"m":0,"t":-1,"u":2}
would be
{"k":"9wjH38dKw823","s":10,"m":0,"t":-1,"u":2}
Does anyone know if this is possible?
Basically the reason for this is because null values are for unchanged properties. A local copy is kept in the javascript that is just updated to reduce traffic to the server. Change values are then merged.
You can create a custom JavaScriptConverter class for the JSON serialization process to use to handle your object, and then put the necessary logic in the Serialize method of that class to exclude the properties that are null.
This article has a clear step-by-step discussion of the process involved in creating it.
You probably would not need to actually implement the Deserialize method (can throw a NotImplementedException) if you are not passing that type of object in as an input parameter to your web services.
Is it possible to store instances of a class in a cookie or in shared objects.
Basically in my application I have an object "Diagram" that the user can create. If they hit save, I want to store the current instance as a cookie and allows them to reload it later.
Alternatively, I could see about getting them to store the saved version on the hard disk. But even then, all I want to save and retreive is my actionscript object.
Is this possible?
I've tried storing the object to SharedObject.data.diag, but when I try to retrieve the object from the cookie doing SharedObject.data.diag as Diag returns null.
http://www.oreilly.de/catalog/9780596529857/chapter/ch17.pdf
Page 10: Serialize typed objects.
You may have issues with deep cloning if you have a complex class.