Acerca de los ejemplos de esta página
Los ejemplos de esta página utilizan el modelo de datos de una aplicación de gestión de proyectos que tiene dos tipos de objetos Realm: Project
y Task. Un Project tiene cero o más Tasks.
Vea el esquema de estas dos clases, Project y Task, a continuación:
import org.bson.types.ObjectId; import io.realm.RealmObject; import io.realm.annotations.PrimaryKey; import io.realm.annotations.RealmClass; import io.realm.annotations.Required; public class ProjectTask extends RealmObject { public ObjectId _id; public String name; public String assignee; public int progressMinutes; public boolean isComplete; public int priority; public String _partition; }
import org.bson.types.ObjectId; import io.realm.RealmList; import io.realm.RealmObject; import io.realm.annotations.PrimaryKey; import io.realm.annotations.RealmClass; import io.realm.annotations.Required; public class Project extends RealmObject { public ObjectId _id; public String name; public RealmList<ProjectTask> tasks = new RealmList<>(); }
import io.realm.RealmObject import io.realm.annotations.PrimaryKey import io.realm.annotations.Required import org.bson.types.ObjectId open class ProjectTask( var _id: ObjectId = ObjectId(), var name: String = "", var assignee: String? = null, var progressMinutes: Int = 0, var isComplete: Boolean = false, var priority: Int = 0, var _partition: String = "" ): RealmObject()
import io.realm.RealmList import io.realm.RealmObject import io.realm.annotations.PrimaryKey import io.realm.annotations.Required import org.bson.types.ObjectId open class Project( var _id: ObjectId = ObjectId(), var name: String = "", var tasks: RealmList<ProjectTask> = RealmList(), ): RealmObject()
Crear un nuevo objeto
Usar realm.createObject() en una transacción para crear una instancia persistente de un objeto Realm en un dominio. Posteriormente, puede modificar el objeto devuelto con otros valores de campo mediante accesores y mutadores.
El siguiente ejemplo demuestra cómo crear un objeto con createObject():
realm.executeTransaction(r -> { // Instantiate the class using the factory function. Turtle turtle = r.createObject(Turtle.class, new ObjectId()); // Configure the instance. turtle.setName("Max"); // Create a TurtleEnthusiast with a primary key. ObjectId primaryKeyValue = new ObjectId(); TurtleEnthusiast turtleEnthusiast = r.createObject(TurtleEnthusiast.class, primaryKeyValue); });
realm.executeTransaction { r: Realm -> // Instantiate the class using the factory function. val turtle = r.createObject(Turtle::class.java, ObjectId()) // Configure the instance. turtle.name = "Max" // Create a TurtleEnthusiast with a primary key. val primaryKeyValue = ObjectId() val turtleEnthusiast = r.createObject( TurtleEnthusiast::class.java, primaryKeyValue ) }
También puedes insertar objetos en un dominio desde JSON. Realm admite la creación de objetos String desde, JSONObject.y tipos InputStream. Realm ignora cualquier propiedad presente en el JSON que no esté definida en el esquema del objeto Realm.
El siguiente ejemplo demuestra cómo crear un solo objeto a partir de JSON con createObjectFromJson() o múltiples objetos a partir de JSON con createAllFromJson():
// Insert from a string realm.executeTransaction(new Realm.Transaction() { public void execute(Realm realm) { realm.createObjectFromJson(Frog.class, "{ name: \"Doctor Cucumber\", age: 1, species: \"bullfrog\", owner: \"Wirt\" }"); } }); // Insert multiple items using an InputStream realm.executeTransaction(new Realm.Transaction() { public void execute(Realm realm) { try { InputStream inputStream = new FileInputStream( new File("path_to_file")); realm.createAllFromJson(Frog.class, inputStream); } catch (IOException e) { throw new RuntimeException(e); } } });
// Insert from a string realm.executeTransaction { realm -> realm.createObjectFromJson( Frog::class.java, "{ name: \"Doctor Cucumber\", age: 1, species: \"bullfrog\", owner: \"Wirt\" }" ) } // Insert multiple items using an InputStream realm.executeTransaction { realm -> try { val inputStream: InputStream = FileInputStream(File("path_to_file")) realm.createAllFromJson(Frog::class.java, inputStream) } catch (e: IOException) { throw RuntimeException(e) } }