SlideShare a Scribd company logo
Realm Mobile Database
Geetika Gupta
Software Consultant
Knoldus Software LLP
AGENDA
➔
What is Realm
➔
Installation
➔
Realm Models
➔
Writes
➔
Queries
➔
Configuring Realm
What is Realm ?
➔
Realm is a cross-platform mobile database, released in July, 2014.
➔
It is a data persistence solution designed specifically for mobile applications.
➔
Realm store data in a universal, table-based format
➔
It is simple as data is directly exposed as objects and queryable by code, removing
the need for ORM's maintenance issues.
➔
Realm is faster than raw SQLite on common operations, while maintaining an
extremely rich feature set.
Installation
➔
You can install realm by adding the following class path dependency to the project
level build.gradle file.
buildscript {
repositories {
jcenter()
}
dependencies {
compile 'io.realm:realm-android:0.87.4'
}
}
Models
➔
Realm model classes are created by extending the RealmObject base class.
public class User extends RealmObject {
private String name;
private int age;
}
➔
Realm supports the following field types:
boolean, byte, short, int, long, float, double, String, Date and byte[].
The integer types byte, short, int, and long are all mapped to the same type (long)
within Realm.
➔
Each model class that extends RealmObject describes the schema for the table in
Realm.
Indexing Properties
➔ The annotation @Index will add a search index to the field.
➔ It supports indexing on the following fields: String, byte, short, Int, long,
boolean and Date
Primary Keys
➔ @PrimaryKey will make the field primary key.
➔ It supports string or Integer (byte, short, int, or long) as primary keys.
➔ @PrimaryKey field implicitly sets the annotation @Index.
➔ copyToRealmOrUpdate() method is used to update an object having primary
key.
➔ It looks for an existing object with the primary key and update it if found, If
no object is found a new object is created.
➔ Calling copyToRealmOrUpdate() on classes without primary keys will throw
an exception.
Transaction Blocks
➔
realm.beginTransaction(): Starts a transaction
➔
realm.commitTransaction(): Commits a transaction, all the changes made will be
written to disk
➔
realm.cancelTransaction(): Cancels a transaction and all the changes will be
discarded.
➔
realm.executeTransaction(): Automatically handles begin/commit, and cancel if an
error happens.
➔
Eg. realm.executeTransaction(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
User user = realm.createObject(User.class);
user.setName("John");
user.setEmail("john@corporation.com");
}
});
Writes
➔
A write transaction is a transaction that is performed to update the state of your realm
object
➔
All write operations (adding, modifying, and removing objects) must be wrapped in
write transactions.
➔
Using write transactions, your data will always be in a consistent state.
➔
A write transaction can either be committed or cancelled. During the commit, all
changes will be written to disk, and the commit will only succeed if all changes can be
persisted
Eg. realm.beginTransaction();
//... add or update objects here ...
realm.commitTransaction();
Writes (cont...)
➔
Realm.executeTransaction() is a method that lets you exclude the begin() and
commit() transaction steps as it handles it internally.
➔
If some Exception occurs inside a transaction, then you need to cancel that
transaction in the catch block
➔
Using executeTransaction() you don’t need to call cancel transaction explicitly, it is
done automatically.
Creating Objects
➔
RealmObjects are strongly tied to a Realm, they should be instantiated through the
Realm directly:
Eg. realm.beginTransaction();
User user = realm.createObject(User.class); // Create a new object
user.setName("John");
user.setEmail("john@corporation.com");
realm.commitTransaction();
➔
It can also be created using realm.copyToRealm(). You can create an instance of an
object first and add it later.
Eg. User user = new User("John");
user.setEmail("john@corporation.com");
// Copy the object to Realm. Any further changes must happen on realmUser
realm.beginTransaction();
User realmUser = realm.copyToRealm(user);
realm.commitTransaction();
➔
When using realm.copyToRealm(), only the returned object is managed by Realm, so
any further changes should be made to returned object.
Auto Updating Objects
RealmObjects are live and auto-updating. Modifying objects that affect the query will
be reflected in the results immediately.
realm.executeTransaction(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
Dog myDog = realm.createObject(Dog.class);
myDog.setName("Fido");
myDog.setAge(1);
}
});
Dog myDog = realm.where(Dog.class).equalTo("age", 1).findFirst();
realm.executeTransaction(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
Dog myPuppy = realm.where(Dog.class).equalTo("age",
1).findFirst();
myPuppy.setAge(2);
}
});
myDog.getAge(); // => 2
Asynchronous Transactions
➔
By using an Asynchronous Transaction, Realm will execute that transaction on the
background thread.
➔
Callbacks can be provided for successful or failure conditions.
Eg. realm.executeTransactionAsync(new Realm.Transaction() {
@Override
public void execute(Realm bgRealm) {
User user = bgRealm.createObject(User.class);
user.setName("John");
user.setEmail("john@corporation.com");
}
}, new Realm.Transaction.OnSuccess() {
@Override
public void onSuccess() {
// Transaction was a success.
}
}, new Realm.Transaction.OnError() {
@Override
public void onError(Throwable error) {
// Transaction failed and was automatically canceled.
}
});
Queries
➔
The following conditions are supported:
between(), greaterThan(), lessThan(), greaterThanOrEqualTo() &
lessThanOrEqualTo()
equalTo() & notEqualTo()
contains(), beginsWith() & endsWith()
isNull() & isNotNull()
isEmpty() & isNotEmpty()
➔
You can also group conditions with “parentheses” to specify order of evaluation:
beginGroup() is your “left parenthesis” and endGroup() your “right parenthesis”:
Eg.
RealmResults<User> r = realm.where(User.class)
.greaterThan("age", 10) //implicit AND
.beginGroup()
.equalTo("name", "Peter")
.or()
.contains("name", "Jo")
.endGroup()
.findAll();
Aggregation Queries
➔
A RealmResults has various aggregation methods:
RealmResults<User> results = realm.where(User.class).findAll();
long sum = results.sum("age").longValue();
long min = results.min("age").longValue();
long max = results.max("age").longValue();
double average = results.average("age");
long matches = results.size();
Deletion Queries
➔ You can delete the results of a query from the Realm:
RealmResults<Dog> results = realm.where(Dog.class).findAll();
// All changes to data must happen in a transaction
realm.executeTransaction(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
results.removeLast(); // remove last object
results.remove(5); // remove a single object
Dog dog = results.get(2);
results.remove(dog);
}
});
Configuring Realm
➔
Realms are equivalent of a database: they contain different kinds of objects.
➔
RealmConfiguration object is used to control all aspects of how a Realm is created.
The minimal configuration usable by Realm is:
RealmConfiguration config = new RealmConfiguration.Builder().build();
The above configuration will point to a file calles default.realm
➔ The RealmConfiguration can be saved as a default configuration.
public class MyActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Realm realm = Realm.getDefaultInstance();
// ... Do something ...
realm.close();
}
}
In Memory Realm
➔
To define an instance for an un-persisted in-memory Realm:
RealmConfiguration myConfig = new RealmConfiguration.Builder()
.name("myrealm.realm")
.inMemory()
.build();
Realm.getInstance(config);
Setting this will create an in-memory Realm instead of saving it to disk.
In-memory Realms might still use disk space if memory is running low, but all files
created by an in-memory Realm will be deleted when the Realm is closed.
DEMO
➔ Github Repository: RealmBookApplication
➔
Realm documentation
➔
Github Repository: Realm-Java
References
Thank You :)
Ad

More Related Content

What's hot (20)

Hypervisors and Virtualization - VMware, Hyper-V, XenServer, and KVM
Hypervisors and Virtualization - VMware, Hyper-V, XenServer, and KVMHypervisors and Virtualization - VMware, Hyper-V, XenServer, and KVM
Hypervisors and Virtualization - VMware, Hyper-V, XenServer, and KVM
vwchu
 
Zoned Storage
Zoned StorageZoned Storage
Zoned Storage
singh.gurjeet
 
DevOps Challenges and Best Practices
DevOps Challenges and Best PracticesDevOps Challenges and Best Practices
DevOps Challenges and Best Practices
Brian Chorba
 
What is Jenkins | Jenkins Tutorial for Beginners | Edureka
What is Jenkins | Jenkins Tutorial for Beginners | EdurekaWhat is Jenkins | Jenkins Tutorial for Beginners | Edureka
What is Jenkins | Jenkins Tutorial for Beginners | Edureka
Edureka!
 
Docker Online Meetup #22: Docker Networking
Docker Online Meetup #22: Docker NetworkingDocker Online Meetup #22: Docker Networking
Docker Online Meetup #22: Docker Networking
Docker, Inc.
 
Container Security
Container SecurityContainer Security
Container Security
Salman Baset
 
Introduction to docker
Introduction to dockerIntroduction to docker
Introduction to docker
Frederik Mogensen
 
Introduction 2 linux
Introduction 2 linuxIntroduction 2 linux
Introduction 2 linux
Papu Kumar
 
Linux basics
Linux basicsLinux basics
Linux basics
BiplabaSamantaray
 
Ansible
AnsibleAnsible
Ansible
Knoldus Inc.
 
Erasure codes and storage tiers on gluster
Erasure codes and storage tiers on glusterErasure codes and storage tiers on gluster
Erasure codes and storage tiers on gluster
Red_Hat_Storage
 
Xen Hypervisor
Xen HypervisorXen Hypervisor
Xen Hypervisor
Susheel Thakur
 
CI CD Basics
CI CD BasicsCI CD Basics
CI CD Basics
Prabhu Ramkumar
 
Docker (Compose) 활용 - 개발 환경 구성하기
Docker (Compose) 활용 - 개발 환경 구성하기Docker (Compose) 활용 - 개발 환경 구성하기
Docker (Compose) 활용 - 개발 환경 구성하기
raccoony
 
Oracle ACFS High Availability NFS Services (HANFS) Part-I
Oracle ACFS High Availability NFS Services (HANFS) Part-IOracle ACFS High Availability NFS Services (HANFS) Part-I
Oracle ACFS High Availability NFS Services (HANFS) Part-I
Anju Garg
 
Union FileSystem - A Building Blocks Of a Container
Union FileSystem - A Building Blocks Of a ContainerUnion FileSystem - A Building Blocks Of a Container
Union FileSystem - A Building Blocks Of a Container
Knoldus Inc.
 
DevOps: Benefits & Future Trends
DevOps: Benefits & Future TrendsDevOps: Benefits & Future Trends
DevOps: Benefits & Future Trends
9 series
 
MySQL InnoDB Cluster and Group Replication in a nutshell hands-on tutorial
MySQL InnoDB Cluster and Group Replication in a nutshell  hands-on tutorialMySQL InnoDB Cluster and Group Replication in a nutshell  hands-on tutorial
MySQL InnoDB Cluster and Group Replication in a nutshell hands-on tutorial
Frederic Descamps
 
VMware ESXi 6.0 Installation Process
VMware ESXi 6.0 Installation ProcessVMware ESXi 6.0 Installation Process
VMware ESXi 6.0 Installation Process
NetProtocol Xpert
 
Unix/Linux Basic Commands and Shell Script
Unix/Linux Basic Commands and Shell ScriptUnix/Linux Basic Commands and Shell Script
Unix/Linux Basic Commands and Shell Script
sbmguys
 
Hypervisors and Virtualization - VMware, Hyper-V, XenServer, and KVM
Hypervisors and Virtualization - VMware, Hyper-V, XenServer, and KVMHypervisors and Virtualization - VMware, Hyper-V, XenServer, and KVM
Hypervisors and Virtualization - VMware, Hyper-V, XenServer, and KVM
vwchu
 
DevOps Challenges and Best Practices
DevOps Challenges and Best PracticesDevOps Challenges and Best Practices
DevOps Challenges and Best Practices
Brian Chorba
 
What is Jenkins | Jenkins Tutorial for Beginners | Edureka
What is Jenkins | Jenkins Tutorial for Beginners | EdurekaWhat is Jenkins | Jenkins Tutorial for Beginners | Edureka
What is Jenkins | Jenkins Tutorial for Beginners | Edureka
Edureka!
 
Docker Online Meetup #22: Docker Networking
Docker Online Meetup #22: Docker NetworkingDocker Online Meetup #22: Docker Networking
Docker Online Meetup #22: Docker Networking
Docker, Inc.
 
Container Security
Container SecurityContainer Security
Container Security
Salman Baset
 
Introduction 2 linux
Introduction 2 linuxIntroduction 2 linux
Introduction 2 linux
Papu Kumar
 
Erasure codes and storage tiers on gluster
Erasure codes and storage tiers on glusterErasure codes and storage tiers on gluster
Erasure codes and storage tiers on gluster
Red_Hat_Storage
 
Docker (Compose) 활용 - 개발 환경 구성하기
Docker (Compose) 활용 - 개발 환경 구성하기Docker (Compose) 활용 - 개발 환경 구성하기
Docker (Compose) 활용 - 개발 환경 구성하기
raccoony
 
Oracle ACFS High Availability NFS Services (HANFS) Part-I
Oracle ACFS High Availability NFS Services (HANFS) Part-IOracle ACFS High Availability NFS Services (HANFS) Part-I
Oracle ACFS High Availability NFS Services (HANFS) Part-I
Anju Garg
 
Union FileSystem - A Building Blocks Of a Container
Union FileSystem - A Building Blocks Of a ContainerUnion FileSystem - A Building Blocks Of a Container
Union FileSystem - A Building Blocks Of a Container
Knoldus Inc.
 
DevOps: Benefits & Future Trends
DevOps: Benefits & Future TrendsDevOps: Benefits & Future Trends
DevOps: Benefits & Future Trends
9 series
 
MySQL InnoDB Cluster and Group Replication in a nutshell hands-on tutorial
MySQL InnoDB Cluster and Group Replication in a nutshell  hands-on tutorialMySQL InnoDB Cluster and Group Replication in a nutshell  hands-on tutorial
MySQL InnoDB Cluster and Group Replication in a nutshell hands-on tutorial
Frederic Descamps
 
VMware ESXi 6.0 Installation Process
VMware ESXi 6.0 Installation ProcessVMware ESXi 6.0 Installation Process
VMware ESXi 6.0 Installation Process
NetProtocol Xpert
 
Unix/Linux Basic Commands and Shell Script
Unix/Linux Basic Commands and Shell ScriptUnix/Linux Basic Commands and Shell Script
Unix/Linux Basic Commands and Shell Script
sbmguys
 

Viewers also liked (20)

Why realm?
Why realm?Why realm?
Why realm?
Leonardo Taehwan Kim
 
Drilling the Async Library
Drilling the Async LibraryDrilling the Async Library
Drilling the Async Library
Knoldus Inc.
 
Getting Started With AureliaJs
Getting Started With AureliaJsGetting Started With AureliaJs
Getting Started With AureliaJs
Knoldus Inc.
 
Introduction to Scala JS
Introduction to Scala JSIntroduction to Scala JS
Introduction to Scala JS
Knoldus Inc.
 
Akka streams
Akka streamsAkka streams
Akka streams
Knoldus Inc.
 
String interpolation
String interpolationString interpolation
String interpolation
Knoldus Inc.
 
Mailchimp and Mandrill - The ‘Hominidae’ kingdom
Mailchimp and Mandrill - The ‘Hominidae’ kingdomMailchimp and Mandrill - The ‘Hominidae’ kingdom
Mailchimp and Mandrill - The ‘Hominidae’ kingdom
Knoldus Inc.
 
Shapeless- Generic programming for Scala
Shapeless- Generic programming for ScalaShapeless- Generic programming for Scala
Shapeless- Generic programming for Scala
Knoldus Inc.
 
Kanban
KanbanKanban
Kanban
Knoldus Inc.
 
Introduction to Java 8
Introduction to Java 8Introduction to Java 8
Introduction to Java 8
Knoldus Inc.
 
Introduction to Scala Macros
Introduction to Scala MacrosIntroduction to Scala Macros
Introduction to Scala Macros
Knoldus Inc.
 
An Introduction to Quill
An Introduction to QuillAn Introduction to Quill
An Introduction to Quill
Knoldus Inc.
 
Mandrill Templates
Mandrill TemplatesMandrill Templates
Mandrill Templates
Knoldus Inc.
 
ANTLR4 and its testing
ANTLR4 and its testingANTLR4 and its testing
ANTLR4 and its testing
Knoldus Inc.
 
Functors, Applicatives and Monads In Scala
Functors, Applicatives and Monads In ScalaFunctors, Applicatives and Monads In Scala
Functors, Applicatives and Monads In Scala
Knoldus Inc.
 
Introduction to ScalaZ
Introduction to ScalaZIntroduction to ScalaZ
Introduction to ScalaZ
Knoldus Inc.
 
Effective way to code in Scala
Effective way to code in ScalaEffective way to code in Scala
Effective way to code in Scala
Knoldus Inc.
 
Introduction to Knockout Js
Introduction to Knockout JsIntroduction to Knockout Js
Introduction to Knockout Js
Knoldus Inc.
 
HTML5, CSS, JavaScript Style guide and coding conventions
HTML5, CSS, JavaScript Style guide and coding conventionsHTML5, CSS, JavaScript Style guide and coding conventions
HTML5, CSS, JavaScript Style guide and coding conventions
Knoldus Inc.
 
Functional programming in Javascript
Functional programming in JavascriptFunctional programming in Javascript
Functional programming in Javascript
Knoldus Inc.
 
Drilling the Async Library
Drilling the Async LibraryDrilling the Async Library
Drilling the Async Library
Knoldus Inc.
 
Getting Started With AureliaJs
Getting Started With AureliaJsGetting Started With AureliaJs
Getting Started With AureliaJs
Knoldus Inc.
 
Introduction to Scala JS
Introduction to Scala JSIntroduction to Scala JS
Introduction to Scala JS
Knoldus Inc.
 
String interpolation
String interpolationString interpolation
String interpolation
Knoldus Inc.
 
Mailchimp and Mandrill - The ‘Hominidae’ kingdom
Mailchimp and Mandrill - The ‘Hominidae’ kingdomMailchimp and Mandrill - The ‘Hominidae’ kingdom
Mailchimp and Mandrill - The ‘Hominidae’ kingdom
Knoldus Inc.
 
Shapeless- Generic programming for Scala
Shapeless- Generic programming for ScalaShapeless- Generic programming for Scala
Shapeless- Generic programming for Scala
Knoldus Inc.
 
Introduction to Java 8
Introduction to Java 8Introduction to Java 8
Introduction to Java 8
Knoldus Inc.
 
Introduction to Scala Macros
Introduction to Scala MacrosIntroduction to Scala Macros
Introduction to Scala Macros
Knoldus Inc.
 
An Introduction to Quill
An Introduction to QuillAn Introduction to Quill
An Introduction to Quill
Knoldus Inc.
 
Mandrill Templates
Mandrill TemplatesMandrill Templates
Mandrill Templates
Knoldus Inc.
 
ANTLR4 and its testing
ANTLR4 and its testingANTLR4 and its testing
ANTLR4 and its testing
Knoldus Inc.
 
Functors, Applicatives and Monads In Scala
Functors, Applicatives and Monads In ScalaFunctors, Applicatives and Monads In Scala
Functors, Applicatives and Monads In Scala
Knoldus Inc.
 
Introduction to ScalaZ
Introduction to ScalaZIntroduction to ScalaZ
Introduction to ScalaZ
Knoldus Inc.
 
Effective way to code in Scala
Effective way to code in ScalaEffective way to code in Scala
Effective way to code in Scala
Knoldus Inc.
 
Introduction to Knockout Js
Introduction to Knockout JsIntroduction to Knockout Js
Introduction to Knockout Js
Knoldus Inc.
 
HTML5, CSS, JavaScript Style guide and coding conventions
HTML5, CSS, JavaScript Style guide and coding conventionsHTML5, CSS, JavaScript Style guide and coding conventions
HTML5, CSS, JavaScript Style guide and coding conventions
Knoldus Inc.
 
Functional programming in Javascript
Functional programming in JavascriptFunctional programming in Javascript
Functional programming in Javascript
Knoldus Inc.
 
Ad

Similar to Realm Mobile Database - An Introduction (20)

Painless Persistence with Realm
Painless Persistence with RealmPainless Persistence with Realm
Painless Persistence with Realm
Christian Melchior
 
Realm Java 2.2.0: Build better apps, faster apps
Realm Java 2.2.0: Build better apps, faster appsRealm Java 2.2.0: Build better apps, faster apps
Realm Java 2.2.0: Build better apps, faster apps
Savvycom - Software Product Development
 
Realm Java 2.2.0: Build better apps, faster apps
Realm Java 2.2.0: Build better apps, faster appsRealm Java 2.2.0: Build better apps, faster apps
Realm Java 2.2.0: Build better apps, faster apps
Savvycom Savvycom
 
Angular JS2 Training Session #1
Angular JS2 Training Session #1Angular JS2 Training Session #1
Angular JS2 Training Session #1
Paras Mendiratta
 
ReactJS
ReactJSReactJS
ReactJS
Ram Murat Sharma
 
Secrets of JavaScript Libraries
Secrets of JavaScript LibrariesSecrets of JavaScript Libraries
Secrets of JavaScript Libraries
jeresig
 
Reactивная тяга
Reactивная тягаReactивная тяга
Reactивная тяга
Vitebsk Miniq
 
Deep Dumpster Diving
Deep Dumpster DivingDeep Dumpster Diving
Deep Dumpster Diving
RonnBlack
 
The Theory Of The Dom
The Theory Of The DomThe Theory Of The Dom
The Theory Of The Dom
kaven yan
 
Joe Walker Interactivewebsites Cometand Dwr
Joe Walker Interactivewebsites Cometand DwrJoe Walker Interactivewebsites Cometand Dwr
Joe Walker Interactivewebsites Cometand Dwr
deimos
 
Ember.js - A JavaScript framework for creating ambitious web applications
Ember.js - A JavaScript framework for creating ambitious web applications  Ember.js - A JavaScript framework for creating ambitious web applications
Ember.js - A JavaScript framework for creating ambitious web applications
Juliana Lucena
 
Painless Persistence in a Disconnected World
Painless Persistence in a Disconnected WorldPainless Persistence in a Disconnected World
Painless Persistence in a Disconnected World
Christian Melchior
 
Building AOL's High Performance, Enterprise Wide Mail Application With Silver...
Building AOL's High Performance, Enterprise Wide Mail Application With Silver...Building AOL's High Performance, Enterprise Wide Mail Application With Silver...
Building AOL's High Performance, Enterprise Wide Mail Application With Silver...
goodfriday
 
Diving in the Flex Data Binding Waters
Diving in the Flex Data Binding WatersDiving in the Flex Data Binding Waters
Diving in the Flex Data Binding Waters
michael.labriola
 
eXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction TrainingeXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction Training
Hoat Le
 
Ajax Fundamentals Web Applications
Ajax Fundamentals Web ApplicationsAjax Fundamentals Web Applications
Ajax Fundamentals Web Applications
dominion
 
Presentation - Windows App Development - II - Mr. Chandan Gupta
Presentation - Windows App Development - II - Mr. Chandan GuptaPresentation - Windows App Development - II - Mr. Chandan Gupta
Presentation - Windows App Development - II - Mr. Chandan Gupta
MobileNepal
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotation
javatwo2011
 
ASP.Net Presentation Part2
ASP.Net Presentation Part2ASP.Net Presentation Part2
ASP.Net Presentation Part2
Neeraj Mathur
 
Unit test candidate solutions
Unit test candidate solutionsUnit test candidate solutions
Unit test candidate solutions
benewu
 
Painless Persistence with Realm
Painless Persistence with RealmPainless Persistence with Realm
Painless Persistence with Realm
Christian Melchior
 
Realm Java 2.2.0: Build better apps, faster apps
Realm Java 2.2.0: Build better apps, faster appsRealm Java 2.2.0: Build better apps, faster apps
Realm Java 2.2.0: Build better apps, faster apps
Savvycom Savvycom
 
Angular JS2 Training Session #1
Angular JS2 Training Session #1Angular JS2 Training Session #1
Angular JS2 Training Session #1
Paras Mendiratta
 
Secrets of JavaScript Libraries
Secrets of JavaScript LibrariesSecrets of JavaScript Libraries
Secrets of JavaScript Libraries
jeresig
 
Reactивная тяга
Reactивная тягаReactивная тяга
Reactивная тяга
Vitebsk Miniq
 
Deep Dumpster Diving
Deep Dumpster DivingDeep Dumpster Diving
Deep Dumpster Diving
RonnBlack
 
The Theory Of The Dom
The Theory Of The DomThe Theory Of The Dom
The Theory Of The Dom
kaven yan
 
Joe Walker Interactivewebsites Cometand Dwr
Joe Walker Interactivewebsites Cometand DwrJoe Walker Interactivewebsites Cometand Dwr
Joe Walker Interactivewebsites Cometand Dwr
deimos
 
Ember.js - A JavaScript framework for creating ambitious web applications
Ember.js - A JavaScript framework for creating ambitious web applications  Ember.js - A JavaScript framework for creating ambitious web applications
Ember.js - A JavaScript framework for creating ambitious web applications
Juliana Lucena
 
Painless Persistence in a Disconnected World
Painless Persistence in a Disconnected WorldPainless Persistence in a Disconnected World
Painless Persistence in a Disconnected World
Christian Melchior
 
Building AOL's High Performance, Enterprise Wide Mail Application With Silver...
Building AOL's High Performance, Enterprise Wide Mail Application With Silver...Building AOL's High Performance, Enterprise Wide Mail Application With Silver...
Building AOL's High Performance, Enterprise Wide Mail Application With Silver...
goodfriday
 
Diving in the Flex Data Binding Waters
Diving in the Flex Data Binding WatersDiving in the Flex Data Binding Waters
Diving in the Flex Data Binding Waters
michael.labriola
 
eXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction TrainingeXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction Training
Hoat Le
 
Ajax Fundamentals Web Applications
Ajax Fundamentals Web ApplicationsAjax Fundamentals Web Applications
Ajax Fundamentals Web Applications
dominion
 
Presentation - Windows App Development - II - Mr. Chandan Gupta
Presentation - Windows App Development - II - Mr. Chandan GuptaPresentation - Windows App Development - II - Mr. Chandan Gupta
Presentation - Windows App Development - II - Mr. Chandan Gupta
MobileNepal
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotation
javatwo2011
 
ASP.Net Presentation Part2
ASP.Net Presentation Part2ASP.Net Presentation Part2
ASP.Net Presentation Part2
Neeraj Mathur
 
Unit test candidate solutions
Unit test candidate solutionsUnit test candidate solutions
Unit test candidate solutions
benewu
 
Ad

More from Knoldus Inc. (20)

Angular Hydration Presentation (FrontEnd)
Angular Hydration Presentation (FrontEnd)Angular Hydration Presentation (FrontEnd)
Angular Hydration Presentation (FrontEnd)
Knoldus Inc.
 
Optimizing Test Execution: Heuristic Algorithm for Self-Healing
Optimizing Test Execution: Heuristic Algorithm for Self-HealingOptimizing Test Execution: Heuristic Algorithm for Self-Healing
Optimizing Test Execution: Heuristic Algorithm for Self-Healing
Knoldus Inc.
 
Self-Healing Test Automation Framework - Healenium
Self-Healing Test Automation Framework - HealeniumSelf-Healing Test Automation Framework - Healenium
Self-Healing Test Automation Framework - Healenium
Knoldus Inc.
 
Kanban Metrics Presentation (Project Management)
Kanban Metrics Presentation (Project Management)Kanban Metrics Presentation (Project Management)
Kanban Metrics Presentation (Project Management)
Knoldus Inc.
 
Java 17 features and implementation.pptx
Java 17 features and implementation.pptxJava 17 features and implementation.pptx
Java 17 features and implementation.pptx
Knoldus Inc.
 
Chaos Mesh Introducing Chaos in Kubernetes
Chaos Mesh Introducing Chaos in KubernetesChaos Mesh Introducing Chaos in Kubernetes
Chaos Mesh Introducing Chaos in Kubernetes
Knoldus Inc.
 
GraalVM - A Step Ahead of JVM Presentation
GraalVM - A Step Ahead of JVM PresentationGraalVM - A Step Ahead of JVM Presentation
GraalVM - A Step Ahead of JVM Presentation
Knoldus Inc.
 
Nomad by HashiCorp Presentation (DevOps)
Nomad by HashiCorp Presentation (DevOps)Nomad by HashiCorp Presentation (DevOps)
Nomad by HashiCorp Presentation (DevOps)
Knoldus Inc.
 
Nomad by HashiCorp Presentation (DevOps)
Nomad by HashiCorp Presentation (DevOps)Nomad by HashiCorp Presentation (DevOps)
Nomad by HashiCorp Presentation (DevOps)
Knoldus Inc.
 
DAPR - Distributed Application Runtime Presentation
DAPR - Distributed Application Runtime PresentationDAPR - Distributed Application Runtime Presentation
DAPR - Distributed Application Runtime Presentation
Knoldus Inc.
 
Introduction to Azure Virtual WAN Presentation
Introduction to Azure Virtual WAN PresentationIntroduction to Azure Virtual WAN Presentation
Introduction to Azure Virtual WAN Presentation
Knoldus Inc.
 
Introduction to Argo Rollouts Presentation
Introduction to Argo Rollouts PresentationIntroduction to Argo Rollouts Presentation
Introduction to Argo Rollouts Presentation
Knoldus Inc.
 
Intro to Azure Container App Presentation
Intro to Azure Container App PresentationIntro to Azure Container App Presentation
Intro to Azure Container App Presentation
Knoldus Inc.
 
Insights Unveiled Test Reporting and Observability Excellence
Insights Unveiled Test Reporting and Observability ExcellenceInsights Unveiled Test Reporting and Observability Excellence
Insights Unveiled Test Reporting and Observability Excellence
Knoldus Inc.
 
Introduction to Splunk Presentation (DevOps)
Introduction to Splunk Presentation (DevOps)Introduction to Splunk Presentation (DevOps)
Introduction to Splunk Presentation (DevOps)
Knoldus Inc.
 
Code Camp - Data Profiling and Quality Analysis Framework
Code Camp - Data Profiling and Quality Analysis FrameworkCode Camp - Data Profiling and Quality Analysis Framework
Code Camp - Data Profiling and Quality Analysis Framework
Knoldus Inc.
 
AWS: Messaging Services in AWS Presentation
AWS: Messaging Services in AWS PresentationAWS: Messaging Services in AWS Presentation
AWS: Messaging Services in AWS Presentation
Knoldus Inc.
 
Amazon Cognito: A Primer on Authentication and Authorization
Amazon Cognito: A Primer on Authentication and AuthorizationAmazon Cognito: A Primer on Authentication and Authorization
Amazon Cognito: A Primer on Authentication and Authorization
Knoldus Inc.
 
ZIO Http A Functional Approach to Scalable and Type-Safe Web Development
ZIO Http A Functional Approach to Scalable and Type-Safe Web DevelopmentZIO Http A Functional Approach to Scalable and Type-Safe Web Development
ZIO Http A Functional Approach to Scalable and Type-Safe Web Development
Knoldus Inc.
 
Managing State & HTTP Requests In Ionic.
Managing State & HTTP Requests In Ionic.Managing State & HTTP Requests In Ionic.
Managing State & HTTP Requests In Ionic.
Knoldus Inc.
 
Angular Hydration Presentation (FrontEnd)
Angular Hydration Presentation (FrontEnd)Angular Hydration Presentation (FrontEnd)
Angular Hydration Presentation (FrontEnd)
Knoldus Inc.
 
Optimizing Test Execution: Heuristic Algorithm for Self-Healing
Optimizing Test Execution: Heuristic Algorithm for Self-HealingOptimizing Test Execution: Heuristic Algorithm for Self-Healing
Optimizing Test Execution: Heuristic Algorithm for Self-Healing
Knoldus Inc.
 
Self-Healing Test Automation Framework - Healenium
Self-Healing Test Automation Framework - HealeniumSelf-Healing Test Automation Framework - Healenium
Self-Healing Test Automation Framework - Healenium
Knoldus Inc.
 
Kanban Metrics Presentation (Project Management)
Kanban Metrics Presentation (Project Management)Kanban Metrics Presentation (Project Management)
Kanban Metrics Presentation (Project Management)
Knoldus Inc.
 
Java 17 features and implementation.pptx
Java 17 features and implementation.pptxJava 17 features and implementation.pptx
Java 17 features and implementation.pptx
Knoldus Inc.
 
Chaos Mesh Introducing Chaos in Kubernetes
Chaos Mesh Introducing Chaos in KubernetesChaos Mesh Introducing Chaos in Kubernetes
Chaos Mesh Introducing Chaos in Kubernetes
Knoldus Inc.
 
GraalVM - A Step Ahead of JVM Presentation
GraalVM - A Step Ahead of JVM PresentationGraalVM - A Step Ahead of JVM Presentation
GraalVM - A Step Ahead of JVM Presentation
Knoldus Inc.
 
Nomad by HashiCorp Presentation (DevOps)
Nomad by HashiCorp Presentation (DevOps)Nomad by HashiCorp Presentation (DevOps)
Nomad by HashiCorp Presentation (DevOps)
Knoldus Inc.
 
Nomad by HashiCorp Presentation (DevOps)
Nomad by HashiCorp Presentation (DevOps)Nomad by HashiCorp Presentation (DevOps)
Nomad by HashiCorp Presentation (DevOps)
Knoldus Inc.
 
DAPR - Distributed Application Runtime Presentation
DAPR - Distributed Application Runtime PresentationDAPR - Distributed Application Runtime Presentation
DAPR - Distributed Application Runtime Presentation
Knoldus Inc.
 
Introduction to Azure Virtual WAN Presentation
Introduction to Azure Virtual WAN PresentationIntroduction to Azure Virtual WAN Presentation
Introduction to Azure Virtual WAN Presentation
Knoldus Inc.
 
Introduction to Argo Rollouts Presentation
Introduction to Argo Rollouts PresentationIntroduction to Argo Rollouts Presentation
Introduction to Argo Rollouts Presentation
Knoldus Inc.
 
Intro to Azure Container App Presentation
Intro to Azure Container App PresentationIntro to Azure Container App Presentation
Intro to Azure Container App Presentation
Knoldus Inc.
 
Insights Unveiled Test Reporting and Observability Excellence
Insights Unveiled Test Reporting and Observability ExcellenceInsights Unveiled Test Reporting and Observability Excellence
Insights Unveiled Test Reporting and Observability Excellence
Knoldus Inc.
 
Introduction to Splunk Presentation (DevOps)
Introduction to Splunk Presentation (DevOps)Introduction to Splunk Presentation (DevOps)
Introduction to Splunk Presentation (DevOps)
Knoldus Inc.
 
Code Camp - Data Profiling and Quality Analysis Framework
Code Camp - Data Profiling and Quality Analysis FrameworkCode Camp - Data Profiling and Quality Analysis Framework
Code Camp - Data Profiling and Quality Analysis Framework
Knoldus Inc.
 
AWS: Messaging Services in AWS Presentation
AWS: Messaging Services in AWS PresentationAWS: Messaging Services in AWS Presentation
AWS: Messaging Services in AWS Presentation
Knoldus Inc.
 
Amazon Cognito: A Primer on Authentication and Authorization
Amazon Cognito: A Primer on Authentication and AuthorizationAmazon Cognito: A Primer on Authentication and Authorization
Amazon Cognito: A Primer on Authentication and Authorization
Knoldus Inc.
 
ZIO Http A Functional Approach to Scalable and Type-Safe Web Development
ZIO Http A Functional Approach to Scalable and Type-Safe Web DevelopmentZIO Http A Functional Approach to Scalable and Type-Safe Web Development
ZIO Http A Functional Approach to Scalable and Type-Safe Web Development
Knoldus Inc.
 
Managing State & HTTP Requests In Ionic.
Managing State & HTTP Requests In Ionic.Managing State & HTTP Requests In Ionic.
Managing State & HTTP Requests In Ionic.
Knoldus Inc.
 

Recently uploaded (20)

How to Install and Activate ListGrabber Plugin
How to Install and Activate ListGrabber PluginHow to Install and Activate ListGrabber Plugin
How to Install and Activate ListGrabber Plugin
eGrabber
 
The Elixir Developer - All Things Open
The Elixir Developer - All Things OpenThe Elixir Developer - All Things Open
The Elixir Developer - All Things Open
Carlo Gilmar Padilla Santana
 
Deploying & Testing Agentforce - End-to-end with Copado - Ewenb Clark
Deploying & Testing Agentforce - End-to-end with Copado - Ewenb ClarkDeploying & Testing Agentforce - End-to-end with Copado - Ewenb Clark
Deploying & Testing Agentforce - End-to-end with Copado - Ewenb Clark
Peter Caitens
 
Programs as Values - Write code and don't get lost
Programs as Values - Write code and don't get lostPrograms as Values - Write code and don't get lost
Programs as Values - Write code and don't get lost
Pierangelo Cecchetto
 
Reinventing Microservices Efficiency and Innovation with Single-Runtime
Reinventing Microservices Efficiency and Innovation with Single-RuntimeReinventing Microservices Efficiency and Innovation with Single-Runtime
Reinventing Microservices Efficiency and Innovation with Single-Runtime
Natan Silnitsky
 
Do not let staffing shortages and limited fiscal view hamper your cause
Do not let staffing shortages and limited fiscal view hamper your causeDo not let staffing shortages and limited fiscal view hamper your cause
Do not let staffing shortages and limited fiscal view hamper your cause
Fexle Services Pvt. Ltd.
 
Orion Context Broker introduction 20250509
Orion Context Broker introduction 20250509Orion Context Broker introduction 20250509
Orion Context Broker introduction 20250509
Fermin Galan
 
Top 12 Most Useful AngularJS Development Tools to Use in 2025
Top 12 Most Useful AngularJS Development Tools to Use in 2025Top 12 Most Useful AngularJS Development Tools to Use in 2025
Top 12 Most Useful AngularJS Development Tools to Use in 2025
GrapesTech Solutions
 
!%& IDM Crack with Internet Download Manager 6.42 Build 32 >
!%& IDM Crack with Internet Download Manager 6.42 Build 32 >!%& IDM Crack with Internet Download Manager 6.42 Build 32 >
!%& IDM Crack with Internet Download Manager 6.42 Build 32 >
Ranking Google
 
Time Estimation: Expert Tips & Proven Project Techniques
Time Estimation: Expert Tips & Proven Project TechniquesTime Estimation: Expert Tips & Proven Project Techniques
Time Estimation: Expert Tips & Proven Project Techniques
Livetecs LLC
 
Serato DJ Pro Crack Latest Version 2025??
Serato DJ Pro Crack Latest Version 2025??Serato DJ Pro Crack Latest Version 2025??
Serato DJ Pro Crack Latest Version 2025??
Web Designer
 
Wilcom Embroidery Studio Crack 2025 For Windows
Wilcom Embroidery Studio Crack 2025 For WindowsWilcom Embroidery Studio Crack 2025 For Windows
Wilcom Embroidery Studio Crack 2025 For Windows
Google
 
[gbgcpp] Let's get comfortable with concepts
[gbgcpp] Let's get comfortable with concepts[gbgcpp] Let's get comfortable with concepts
[gbgcpp] Let's get comfortable with concepts
Dimitrios Platis
 
Autodesk Inventor Crack (2025) Latest
Autodesk Inventor    Crack (2025) LatestAutodesk Inventor    Crack (2025) Latest
Autodesk Inventor Crack (2025) Latest
Google
 
Top Magento Hyvä Theme Features That Make It Ideal for E-commerce.pdf
Top Magento Hyvä Theme Features That Make It Ideal for E-commerce.pdfTop Magento Hyvä Theme Features That Make It Ideal for E-commerce.pdf
Top Magento Hyvä Theme Features That Make It Ideal for E-commerce.pdf
evrigsolution
 
Passive House Canada Conference 2025 Presentation [Final]_v4.ppt
Passive House Canada Conference 2025 Presentation [Final]_v4.pptPassive House Canada Conference 2025 Presentation [Final]_v4.ppt
Passive House Canada Conference 2025 Presentation [Final]_v4.ppt
IES VE
 
Surviving a Downturn Making Smarter Portfolio Decisions with OnePlan - Webina...
Surviving a Downturn Making Smarter Portfolio Decisions with OnePlan - Webina...Surviving a Downturn Making Smarter Portfolio Decisions with OnePlan - Webina...
Surviving a Downturn Making Smarter Portfolio Decisions with OnePlan - Webina...
OnePlan Solutions
 
Adobe Audition Crack FRESH Version 2025 FREE
Adobe Audition Crack FRESH Version 2025 FREEAdobe Audition Crack FRESH Version 2025 FREE
Adobe Audition Crack FRESH Version 2025 FREE
zafranwaqar90
 
Download MathType Crack Version 2025???
Download MathType Crack  Version 2025???Download MathType Crack  Version 2025???
Download MathType Crack Version 2025???
Google
 
Medical Device Cybersecurity Threat & Risk Scoring
Medical Device Cybersecurity Threat & Risk ScoringMedical Device Cybersecurity Threat & Risk Scoring
Medical Device Cybersecurity Threat & Risk Scoring
ICS
 
How to Install and Activate ListGrabber Plugin
How to Install and Activate ListGrabber PluginHow to Install and Activate ListGrabber Plugin
How to Install and Activate ListGrabber Plugin
eGrabber
 
Deploying & Testing Agentforce - End-to-end with Copado - Ewenb Clark
Deploying & Testing Agentforce - End-to-end with Copado - Ewenb ClarkDeploying & Testing Agentforce - End-to-end with Copado - Ewenb Clark
Deploying & Testing Agentforce - End-to-end with Copado - Ewenb Clark
Peter Caitens
 
Programs as Values - Write code and don't get lost
Programs as Values - Write code and don't get lostPrograms as Values - Write code and don't get lost
Programs as Values - Write code and don't get lost
Pierangelo Cecchetto
 
Reinventing Microservices Efficiency and Innovation with Single-Runtime
Reinventing Microservices Efficiency and Innovation with Single-RuntimeReinventing Microservices Efficiency and Innovation with Single-Runtime
Reinventing Microservices Efficiency and Innovation with Single-Runtime
Natan Silnitsky
 
Do not let staffing shortages and limited fiscal view hamper your cause
Do not let staffing shortages and limited fiscal view hamper your causeDo not let staffing shortages and limited fiscal view hamper your cause
Do not let staffing shortages and limited fiscal view hamper your cause
Fexle Services Pvt. Ltd.
 
Orion Context Broker introduction 20250509
Orion Context Broker introduction 20250509Orion Context Broker introduction 20250509
Orion Context Broker introduction 20250509
Fermin Galan
 
Top 12 Most Useful AngularJS Development Tools to Use in 2025
Top 12 Most Useful AngularJS Development Tools to Use in 2025Top 12 Most Useful AngularJS Development Tools to Use in 2025
Top 12 Most Useful AngularJS Development Tools to Use in 2025
GrapesTech Solutions
 
!%& IDM Crack with Internet Download Manager 6.42 Build 32 >
!%& IDM Crack with Internet Download Manager 6.42 Build 32 >!%& IDM Crack with Internet Download Manager 6.42 Build 32 >
!%& IDM Crack with Internet Download Manager 6.42 Build 32 >
Ranking Google
 
Time Estimation: Expert Tips & Proven Project Techniques
Time Estimation: Expert Tips & Proven Project TechniquesTime Estimation: Expert Tips & Proven Project Techniques
Time Estimation: Expert Tips & Proven Project Techniques
Livetecs LLC
 
Serato DJ Pro Crack Latest Version 2025??
Serato DJ Pro Crack Latest Version 2025??Serato DJ Pro Crack Latest Version 2025??
Serato DJ Pro Crack Latest Version 2025??
Web Designer
 
Wilcom Embroidery Studio Crack 2025 For Windows
Wilcom Embroidery Studio Crack 2025 For WindowsWilcom Embroidery Studio Crack 2025 For Windows
Wilcom Embroidery Studio Crack 2025 For Windows
Google
 
[gbgcpp] Let's get comfortable with concepts
[gbgcpp] Let's get comfortable with concepts[gbgcpp] Let's get comfortable with concepts
[gbgcpp] Let's get comfortable with concepts
Dimitrios Platis
 
Autodesk Inventor Crack (2025) Latest
Autodesk Inventor    Crack (2025) LatestAutodesk Inventor    Crack (2025) Latest
Autodesk Inventor Crack (2025) Latest
Google
 
Top Magento Hyvä Theme Features That Make It Ideal for E-commerce.pdf
Top Magento Hyvä Theme Features That Make It Ideal for E-commerce.pdfTop Magento Hyvä Theme Features That Make It Ideal for E-commerce.pdf
Top Magento Hyvä Theme Features That Make It Ideal for E-commerce.pdf
evrigsolution
 
Passive House Canada Conference 2025 Presentation [Final]_v4.ppt
Passive House Canada Conference 2025 Presentation [Final]_v4.pptPassive House Canada Conference 2025 Presentation [Final]_v4.ppt
Passive House Canada Conference 2025 Presentation [Final]_v4.ppt
IES VE
 
Surviving a Downturn Making Smarter Portfolio Decisions with OnePlan - Webina...
Surviving a Downturn Making Smarter Portfolio Decisions with OnePlan - Webina...Surviving a Downturn Making Smarter Portfolio Decisions with OnePlan - Webina...
Surviving a Downturn Making Smarter Portfolio Decisions with OnePlan - Webina...
OnePlan Solutions
 
Adobe Audition Crack FRESH Version 2025 FREE
Adobe Audition Crack FRESH Version 2025 FREEAdobe Audition Crack FRESH Version 2025 FREE
Adobe Audition Crack FRESH Version 2025 FREE
zafranwaqar90
 
Download MathType Crack Version 2025???
Download MathType Crack  Version 2025???Download MathType Crack  Version 2025???
Download MathType Crack Version 2025???
Google
 
Medical Device Cybersecurity Threat & Risk Scoring
Medical Device Cybersecurity Threat & Risk ScoringMedical Device Cybersecurity Threat & Risk Scoring
Medical Device Cybersecurity Threat & Risk Scoring
ICS
 

Realm Mobile Database - An Introduction

  • 1. Realm Mobile Database Geetika Gupta Software Consultant Knoldus Software LLP
  • 2. AGENDA ➔ What is Realm ➔ Installation ➔ Realm Models ➔ Writes ➔ Queries ➔ Configuring Realm
  • 3. What is Realm ? ➔ Realm is a cross-platform mobile database, released in July, 2014. ➔ It is a data persistence solution designed specifically for mobile applications. ➔ Realm store data in a universal, table-based format ➔ It is simple as data is directly exposed as objects and queryable by code, removing the need for ORM's maintenance issues. ➔ Realm is faster than raw SQLite on common operations, while maintaining an extremely rich feature set.
  • 4. Installation ➔ You can install realm by adding the following class path dependency to the project level build.gradle file. buildscript { repositories { jcenter() } dependencies { compile 'io.realm:realm-android:0.87.4' } }
  • 5. Models ➔ Realm model classes are created by extending the RealmObject base class. public class User extends RealmObject { private String name; private int age; } ➔ Realm supports the following field types: boolean, byte, short, int, long, float, double, String, Date and byte[]. The integer types byte, short, int, and long are all mapped to the same type (long) within Realm. ➔ Each model class that extends RealmObject describes the schema for the table in Realm.
  • 6. Indexing Properties ➔ The annotation @Index will add a search index to the field. ➔ It supports indexing on the following fields: String, byte, short, Int, long, boolean and Date
  • 7. Primary Keys ➔ @PrimaryKey will make the field primary key. ➔ It supports string or Integer (byte, short, int, or long) as primary keys. ➔ @PrimaryKey field implicitly sets the annotation @Index. ➔ copyToRealmOrUpdate() method is used to update an object having primary key. ➔ It looks for an existing object with the primary key and update it if found, If no object is found a new object is created. ➔ Calling copyToRealmOrUpdate() on classes without primary keys will throw an exception.
  • 8. Transaction Blocks ➔ realm.beginTransaction(): Starts a transaction ➔ realm.commitTransaction(): Commits a transaction, all the changes made will be written to disk ➔ realm.cancelTransaction(): Cancels a transaction and all the changes will be discarded. ➔ realm.executeTransaction(): Automatically handles begin/commit, and cancel if an error happens. ➔ Eg. realm.executeTransaction(new Realm.Transaction() { @Override public void execute(Realm realm) { User user = realm.createObject(User.class); user.setName("John"); user.setEmail("john@corporation.com"); } });
  • 9. Writes ➔ A write transaction is a transaction that is performed to update the state of your realm object ➔ All write operations (adding, modifying, and removing objects) must be wrapped in write transactions. ➔ Using write transactions, your data will always be in a consistent state. ➔ A write transaction can either be committed or cancelled. During the commit, all changes will be written to disk, and the commit will only succeed if all changes can be persisted Eg. realm.beginTransaction(); //... add or update objects here ... realm.commitTransaction();
  • 10. Writes (cont...) ➔ Realm.executeTransaction() is a method that lets you exclude the begin() and commit() transaction steps as it handles it internally. ➔ If some Exception occurs inside a transaction, then you need to cancel that transaction in the catch block ➔ Using executeTransaction() you don’t need to call cancel transaction explicitly, it is done automatically.
  • 11. Creating Objects ➔ RealmObjects are strongly tied to a Realm, they should be instantiated through the Realm directly: Eg. realm.beginTransaction(); User user = realm.createObject(User.class); // Create a new object user.setName("John"); user.setEmail("john@corporation.com"); realm.commitTransaction(); ➔ It can also be created using realm.copyToRealm(). You can create an instance of an object first and add it later. Eg. User user = new User("John"); user.setEmail("john@corporation.com"); // Copy the object to Realm. Any further changes must happen on realmUser realm.beginTransaction(); User realmUser = realm.copyToRealm(user); realm.commitTransaction(); ➔ When using realm.copyToRealm(), only the returned object is managed by Realm, so any further changes should be made to returned object.
  • 12. Auto Updating Objects RealmObjects are live and auto-updating. Modifying objects that affect the query will be reflected in the results immediately. realm.executeTransaction(new Realm.Transaction() { @Override public void execute(Realm realm) { Dog myDog = realm.createObject(Dog.class); myDog.setName("Fido"); myDog.setAge(1); } }); Dog myDog = realm.where(Dog.class).equalTo("age", 1).findFirst(); realm.executeTransaction(new Realm.Transaction() { @Override public void execute(Realm realm) { Dog myPuppy = realm.where(Dog.class).equalTo("age", 1).findFirst(); myPuppy.setAge(2); } }); myDog.getAge(); // => 2
  • 13. Asynchronous Transactions ➔ By using an Asynchronous Transaction, Realm will execute that transaction on the background thread. ➔ Callbacks can be provided for successful or failure conditions. Eg. realm.executeTransactionAsync(new Realm.Transaction() { @Override public void execute(Realm bgRealm) { User user = bgRealm.createObject(User.class); user.setName("John"); user.setEmail("john@corporation.com"); } }, new Realm.Transaction.OnSuccess() { @Override public void onSuccess() { // Transaction was a success. } }, new Realm.Transaction.OnError() { @Override public void onError(Throwable error) { // Transaction failed and was automatically canceled. } });
  • 14. Queries ➔ The following conditions are supported: between(), greaterThan(), lessThan(), greaterThanOrEqualTo() & lessThanOrEqualTo() equalTo() & notEqualTo() contains(), beginsWith() & endsWith() isNull() & isNotNull() isEmpty() & isNotEmpty() ➔ You can also group conditions with “parentheses” to specify order of evaluation: beginGroup() is your “left parenthesis” and endGroup() your “right parenthesis”: Eg. RealmResults<User> r = realm.where(User.class) .greaterThan("age", 10) //implicit AND .beginGroup() .equalTo("name", "Peter") .or() .contains("name", "Jo") .endGroup() .findAll();
  • 15. Aggregation Queries ➔ A RealmResults has various aggregation methods: RealmResults<User> results = realm.where(User.class).findAll(); long sum = results.sum("age").longValue(); long min = results.min("age").longValue(); long max = results.max("age").longValue(); double average = results.average("age"); long matches = results.size(); Deletion Queries ➔ You can delete the results of a query from the Realm: RealmResults<Dog> results = realm.where(Dog.class).findAll(); // All changes to data must happen in a transaction realm.executeTransaction(new Realm.Transaction() { @Override public void execute(Realm realm) { results.removeLast(); // remove last object results.remove(5); // remove a single object Dog dog = results.get(2); results.remove(dog); } });
  • 16. Configuring Realm ➔ Realms are equivalent of a database: they contain different kinds of objects. ➔ RealmConfiguration object is used to control all aspects of how a Realm is created. The minimal configuration usable by Realm is: RealmConfiguration config = new RealmConfiguration.Builder().build(); The above configuration will point to a file calles default.realm ➔ The RealmConfiguration can be saved as a default configuration. public class MyActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Realm realm = Realm.getDefaultInstance(); // ... Do something ... realm.close(); } }
  • 17. In Memory Realm ➔ To define an instance for an un-persisted in-memory Realm: RealmConfiguration myConfig = new RealmConfiguration.Builder() .name("myrealm.realm") .inMemory() .build(); Realm.getInstance(config); Setting this will create an in-memory Realm instead of saving it to disk. In-memory Realms might still use disk space if memory is running low, but all files created by an in-memory Realm will be deleted when the Realm is closed.
  • 18. DEMO ➔ Github Repository: RealmBookApplication
  翻译: