SlideShare a Scribd company logo
1 of 25
Download to read offline
Realm JAVA 2.2.0
Build better apps, faster apps
Author: Doi Thanh Thinh
Savvycom JSC
1Doi Thanh Thinh - Savvycom JSC
SQLite problems
• Queries too slow
• Complex
relationships
• Nest SELECT, JOIN
• Migration
2Doi Thanh Thinh - Savvycom JSC
SQLite problems
No-SQL SQLite
A
B
D
G
C
FE
Realm.getA().getC().getF();
SELECT user.name, user.email
FROM user
INNER JOIN shop ON user.id =
shop.userid INNER JOIN city ON
user.cityid = city.id WHERE user.name =
'the flash'
3Doi Thanh Thinh - Savvycom JSC
1. What Realm Is
2. Compare and contrast with SQLite
3. Implement Realm
4. Example
Overview
4Doi Thanh Thinh - Savvycom JSC
 Realm is a mobile database and a replacement
for SQLite
 Core is written in C++
 Cross platform mobile database
What Realm Is
5Doi Thanh Thinh - Savvycom JSC
 Advantages
 Faster than SQLite
 Support in-memory database
 Custom migrating
 The Realm file can be stored encrypted on disk by standard AES-256
encryption
 Missing Features
 Auto-incrementing ids
 Compoud primary keys
Features
6Doi Thanh Thinh - Savvycom JSC
Prerequisites
• Do not support Java outside of Android at the moment
• Android Studio >= 1.5.1
• A recent version of the Android SDK
• JDK version >=7
• Support all Android versions since API Level 9 (Android
2.3 Gingerbread & above)
7Doi Thanh Thinh - Savvycom JSC
Benchmarks
Faster than SQLite (up to 10x speed up over raw SQLite )
8Doi Thanh Thinh - Savvycom JSC
Benchmarks
9Doi Thanh Thinh - Savvycom JSC
Benchmarks
10Doi Thanh Thinh - Savvycom JSC
Step 1: Add the following class path dependency to the project level
build.gradle file.
buildscript {
repositories {
jcenter()
}
dependencies {
classpath "io.realm:realm-gradle-plugin:2.2.0"
}
}
Step 2: Apply the realm-android plugin to the top of application level
build.gradle file.
apply plugin: 'realm-android'
Installation
11Doi Thanh Thinh - Savvycom JSC
 Models: Realm model classes are created by
extending the RealmObject base class.
public class User extends RealmObject {
private String name;
private int age;
@Ignore
private int sessionId;
// Standard getters & setters generated by your IDE…
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public int getAge() { return age; }
public void setAge(int age) { this.age = age; }
public int getSessionId() { return sessionId; }
public void setSessionId(int sessionId) { this.sessionId = sessionId; }
}
Implement Realm
Custom methods:
public boolean hasLongName() {
return name.length() > 7;
}
12Doi Thanh Thinh - Savvycom JSC
 Field types:
Supports the following field types:
boolean, byte, short, int, long, float, double, String, Date and
byte[].
The boxed types Boolean, Byte, Short, Integer, Long, Float and
Double
 @Required: used to tell Realm to enforce checks to disallow
null values
 @Ignore: a field should not be persisted to disk
 @PrimaryKey : a primary key field
 @Index will add a search index to the field
Implement Realm: Types fields
13Doi Thanh Thinh - Savvycom JSC
Relationships
N – 1
public class Contact extends
RealmObject {
private Email email;
// Other fields…
}
N - N
public class Contact extends
RealmObject {
public RealmList<Email> emails;
// Other fields…
}
You can use this to model
both one-to-many, and
many-to-many
relationships.
14Doi Thanh Thinh - Savvycom JSC
Conditions of Queries
 between(), greaterThan(), lessThan(), greaterThanOrEqualTo() &
lessThanOrEqualTo()
 equalTo() & notEqualTo()
 contains(), beginsWith() & endsWith()
 isNull() & isNotNull()
 isEmpty() & isNotEmpty()
15Doi Thanh Thinh - Savvycom JSC
RealmResults<User> r = realm.where(User.class)
.greaterThan("age", 10) //implicit AND
.beginGroup()
.equalTo("name", "Peter")
.or()
.contains("name", "Jo")
.endGroup()
.findAll();
Conditions of Queries
RealmResults<User> result = realm.where(User.class).findAll();
result = result.sort("age"); // Sort ascending
result = result.sort("age", Sort.DESCENDING);
16Doi Thanh Thinh - Savvycom JSC
Insert
Realm myRealm = Realm.getInstance(this);
Person person2 = new Person();
person2.setId("U2");
person2.setName("John");
myRealm.beginTransaction();
// copy the object to realm. Any further changes must happen on realmPerson
Person realmPerson = myRealm.copyToRealm(person2);
myRealm.commitTransaction();
Dog dog1 = myRealm.createObject(Dog.class);
// Set its fields
dog1.setId("A");
dog1.setName("Fido");
dog1.setColor("Brown");
myRealm.commitTransaction(); 17Doi Thanh Thinh - Savvycom JSC
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
Auto-Updating
Auto Update Realtime
18Doi Thanh Thinh - Savvycom JSC
Example
public class Person extends
RealmObject {
private String id;
private String name;
private RealmList<Dog> dogs;
// getters and setters
}
public class Dog extends RealmObject {
private String id;
private String name;
private String color;
// getters and setters
}
19Doi Thanh Thinh - Savvycom JSC
Example
// persons => [U1,U2]
RealmResults<Person> persons = realm.where(Person.class)
.equalTo("dogs.color", "Brown")
.findAll();
// r1 => [U1,U2]
RealmResults<Person> r1 = realm.where(Person.class)
.equalTo("dogs.name", "Fluffy")
.equalTo("dogs.color", "Brown")
.findAll();
// r2 => [U2]
RealmResults<Person> r2 = realm.where(Person.class)
.equalTo("dogs.name", "Fluffy")
.findAll()
.where()
.equalTo("dogs.color", "Brown")
.findAll();
.where()
.equalTo("dogs.color", "Yellow")
.findAll();
20Doi Thanh Thinh - Savvycom JSC
Insert/Update
Asynchronous Transactions:
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.
}
});
Avoid blocking the UI thread
21Doi Thanh Thinh - Savvycom JSC
Delete
// obtain the results of a query
final 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) {
// remove single match
results.deleteFirstFromRealm();
results.deleteLastFromRealm();
// remove a single object
Dog dog = results.get(5);
dog.deleteFromRealm();
// Delete all matches
results.deleteAllFromRealm();
}
});
22Doi Thanh Thinh - Savvycom JSC
JSON
• It is possible to add RealmObjects represented as JSON directly to Realm .
they are represented as a String, a JSONObject or an InputStream
• Single object is added through Realm.createObjectFromJson()
• lists of objects are added using Realm.createAllFromJson().
// A RealmObject that represents a city
public class City extends RealmObject {
private String city;
private int id;
// getters and setters left out ...
}
// Insert from a string
realm.executeTransaction(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
realm.createObjectFromJson(City.class, "{ city: "Copenhagen", id: 1 }");
}
}); 23Doi Thanh Thinh - Savvycom JSC
Demo
24Doi Thanh Thinh - Savvycom JSC
Resources
Official Site for Realm
https://realm.io/
Realm Full API for Java
http://realm.io/docs/java/latest/api/
Realm Browser:
https://github.com/realm/realm-cocoa/tree/master/tools/RealmBrowser
Github:
https://github.com/thinhdt/DemoRealm
25Doi Thanh Thinh - Savvycom JSC

More Related Content

What's hot

Aesthetics and the Beauty of an Architecture
Aesthetics and the Beauty of an ArchitectureAesthetics and the Beauty of an Architecture
Aesthetics and the Beauty of an ArchitectureTom Scott
 
Aplikasi rawat-inap-vbnet
Aplikasi rawat-inap-vbnetAplikasi rawat-inap-vbnet
Aplikasi rawat-inap-vbnetDiaz Alfahrezy
 
Jquery dojo slides
Jquery dojo slidesJquery dojo slides
Jquery dojo slideshelenmga
 
Get Back in Control of Your SQL with jOOQ at #Java2Days
Get Back in Control of Your SQL with jOOQ at #Java2DaysGet Back in Control of Your SQL with jOOQ at #Java2Days
Get Back in Control of Your SQL with jOOQ at #Java2DaysLukas Eder
 
Overview of The Scala Based Lift Web Framework
Overview of The Scala Based Lift Web FrameworkOverview of The Scala Based Lift Web Framework
Overview of The Scala Based Lift Web FrameworkIndicThreads
 
BDD, ATDD, Page Objects: The Road to Sustainable Web Testing
BDD, ATDD, Page Objects: The Road to Sustainable Web TestingBDD, ATDD, Page Objects: The Road to Sustainable Web Testing
BDD, ATDD, Page Objects: The Road to Sustainable Web TestingJohn Ferguson Smart Limited
 
The Ring programming language version 1.9 book - Part 53 of 210
The Ring programming language version 1.9 book - Part 53 of 210The Ring programming language version 1.9 book - Part 53 of 210
The Ring programming language version 1.9 book - Part 53 of 210Mahmoud Samir Fayed
 
Single page webapps & javascript-testing
Single page webapps & javascript-testingSingle page webapps & javascript-testing
Single page webapps & javascript-testingsmontanari
 
Writing SOLID C++ [gbgcpp meetup @ Zenseact]
Writing SOLID C++ [gbgcpp meetup @ Zenseact]Writing SOLID C++ [gbgcpp meetup @ Zenseact]
Writing SOLID C++ [gbgcpp meetup @ Zenseact]Dimitrios Platis
 
Intoduction on Playframework
Intoduction on PlayframeworkIntoduction on Playframework
Intoduction on PlayframeworkKnoldus Inc.
 
Windows Azure Storage
Windows Azure StorageWindows Azure Storage
Windows Azure Storagegoodfriday
 
Graph Database workshop
Graph Database workshopGraph Database workshop
Graph Database workshopJeremy Deane
 
Certified Pseudonym Colligated with Master Secret Key
Certified Pseudonym Colligated with Master Secret KeyCertified Pseudonym Colligated with Master Secret Key
Certified Pseudonym Colligated with Master Secret KeyVijay Pasupathinathan, PhD
 
What makes a good bug report?
What makes a good bug report?What makes a good bug report?
What makes a good bug report?Rahul Premraj
 
MQTT and Java - Client and Broker Examples
MQTT and Java - Client and Broker ExamplesMQTT and Java - Client and Broker Examples
MQTT and Java - Client and Broker ExamplesMicha Kops
 
Maven + Jsf + Richfaces + Jxl + Jdbc - Complete Code Example
Maven + Jsf + Richfaces + Jxl + Jdbc - Complete Code ExampleMaven + Jsf + Richfaces + Jxl + Jdbc - Complete Code Example
Maven + Jsf + Richfaces + Jxl + Jdbc - Complete Code ExampleNikhil Bhalwankar
 

What's hot (18)

Aesthetics and the Beauty of an Architecture
Aesthetics and the Beauty of an ArchitectureAesthetics and the Beauty of an Architecture
Aesthetics and the Beauty of an Architecture
 
Aplikasi rawat-inap-vbnet
Aplikasi rawat-inap-vbnetAplikasi rawat-inap-vbnet
Aplikasi rawat-inap-vbnet
 
Jquery dojo slides
Jquery dojo slidesJquery dojo slides
Jquery dojo slides
 
Get Back in Control of Your SQL with jOOQ at #Java2Days
Get Back in Control of Your SQL with jOOQ at #Java2DaysGet Back in Control of Your SQL with jOOQ at #Java2Days
Get Back in Control of Your SQL with jOOQ at #Java2Days
 
Overview of The Scala Based Lift Web Framework
Overview of The Scala Based Lift Web FrameworkOverview of The Scala Based Lift Web Framework
Overview of The Scala Based Lift Web Framework
 
Overview Of Lift Framework
Overview Of Lift FrameworkOverview Of Lift Framework
Overview Of Lift Framework
 
BDD, ATDD, Page Objects: The Road to Sustainable Web Testing
BDD, ATDD, Page Objects: The Road to Sustainable Web TestingBDD, ATDD, Page Objects: The Road to Sustainable Web Testing
BDD, ATDD, Page Objects: The Road to Sustainable Web Testing
 
The Ring programming language version 1.9 book - Part 53 of 210
The Ring programming language version 1.9 book - Part 53 of 210The Ring programming language version 1.9 book - Part 53 of 210
The Ring programming language version 1.9 book - Part 53 of 210
 
Single page webapps & javascript-testing
Single page webapps & javascript-testingSingle page webapps & javascript-testing
Single page webapps & javascript-testing
 
Writing SOLID C++ [gbgcpp meetup @ Zenseact]
Writing SOLID C++ [gbgcpp meetup @ Zenseact]Writing SOLID C++ [gbgcpp meetup @ Zenseact]
Writing SOLID C++ [gbgcpp meetup @ Zenseact]
 
Intoduction on Playframework
Intoduction on PlayframeworkIntoduction on Playframework
Intoduction on Playframework
 
Windows Azure Storage
Windows Azure StorageWindows Azure Storage
Windows Azure Storage
 
Graph Database workshop
Graph Database workshopGraph Database workshop
Graph Database workshop
 
Certified Pseudonym Colligated with Master Secret Key
Certified Pseudonym Colligated with Master Secret KeyCertified Pseudonym Colligated with Master Secret Key
Certified Pseudonym Colligated with Master Secret Key
 
What makes a good bug report?
What makes a good bug report?What makes a good bug report?
What makes a good bug report?
 
分散式系統
分散式系統分散式系統
分散式系統
 
MQTT and Java - Client and Broker Examples
MQTT and Java - Client and Broker ExamplesMQTT and Java - Client and Broker Examples
MQTT and Java - Client and Broker Examples
 
Maven + Jsf + Richfaces + Jxl + Jdbc - Complete Code Example
Maven + Jsf + Richfaces + Jxl + Jdbc - Complete Code ExampleMaven + Jsf + Richfaces + Jxl + Jdbc - Complete Code Example
Maven + Jsf + Richfaces + Jxl + Jdbc - Complete Code Example
 

Viewers also liked

Viewers also liked (6)

Reactive programming with RxAndroid
Reactive programming with RxAndroidReactive programming with RxAndroid
Reactive programming with RxAndroid
 
Building Apps Faster with Lightning and Winter '17
Building Apps Faster with Lightning and Winter '17Building Apps Faster with Lightning and Winter '17
Building Apps Faster with Lightning and Winter '17
 
Savvycom Profile
Savvycom ProfileSavvycom Profile
Savvycom Profile
 
Vietnam Mobile Report Q1 2016
Vietnam Mobile Report Q1 2016Vietnam Mobile Report Q1 2016
Vietnam Mobile Report Q1 2016
 
Vietnam Mobile Report Q3 2016
Vietnam Mobile Report Q3 2016Vietnam Mobile Report Q3 2016
Vietnam Mobile Report Q3 2016
 
Vietnam E-commerce Report 2016
Vietnam E-commerce Report 2016 Vietnam E-commerce Report 2016
Vietnam E-commerce Report 2016
 

Similar to Realm Java 2.2.0: Build better apps, faster apps

Realm Mobile Database - An Introduction
Realm Mobile Database - An IntroductionRealm Mobile Database - An Introduction
Realm Mobile Database - An IntroductionKnoldus Inc.
 
Present realm
Present realmPresent realm
Present realmthinhit
 
Networking and Data Access with Eqela
Networking and Data Access with EqelaNetworking and Data Access with Eqela
Networking and Data Access with Eqelajobandesther
 
Joe Walker Interactivewebsites Cometand Dwr
Joe Walker Interactivewebsites Cometand DwrJoe Walker Interactivewebsites Cometand Dwr
Joe Walker Interactivewebsites Cometand Dwrdeimos
 
Struts 2 + Spring
Struts 2 + SpringStruts 2 + Spring
Struts 2 + SpringBryan Hsueh
 
Painless Persistence with Realm
Painless Persistence with RealmPainless Persistence with Realm
Painless Persistence with RealmChristian Melchior
 
The State of JavaScript (2015)
The State of JavaScript (2015)The State of JavaScript (2015)
The State of JavaScript (2015)Domenic Denicola
 
Testing in android
Testing in androidTesting in android
Testing in androidjtrindade
 
Painless Persistence in a Disconnected World
Painless Persistence in a Disconnected WorldPainless Persistence in a Disconnected World
Painless Persistence in a Disconnected WorldChristian Melchior
 
Hi, I need some one to help me with Design a client-server Chat so.pdf
Hi, I need some one to help me with Design a client-server Chat so.pdfHi, I need some one to help me with Design a client-server Chat so.pdf
Hi, I need some one to help me with Design a client-server Chat so.pdffashiongallery1
 
HTML5 for the Silverlight Guy
HTML5 for the Silverlight GuyHTML5 for the Silverlight Guy
HTML5 for the Silverlight GuyDavid Padbury
 
Android and the Seven Dwarfs from Devox'15
Android and the Seven Dwarfs from Devox'15Android and the Seven Dwarfs from Devox'15
Android and the Seven Dwarfs from Devox'15Murat Yener
 
Launching Beeline with Firebase
Launching Beeline with FirebaseLaunching Beeline with Firebase
Launching Beeline with FirebaseChetan Padia
 
Addressing Scenario
Addressing ScenarioAddressing Scenario
Addressing ScenarioTara Hardin
 

Similar to Realm Java 2.2.0: Build better apps, faster apps (20)

Realm Mobile Database - An Introduction
Realm Mobile Database - An IntroductionRealm Mobile Database - An Introduction
Realm Mobile Database - An Introduction
 
Present realm
Present realmPresent realm
Present realm
 
Networking and Data Access with Eqela
Networking and Data Access with EqelaNetworking and Data Access with Eqela
Networking and Data Access with Eqela
 
Joe Walker Interactivewebsites Cometand Dwr
Joe Walker Interactivewebsites Cometand DwrJoe Walker Interactivewebsites Cometand Dwr
Joe Walker Interactivewebsites Cometand Dwr
 
Struts 2 + Spring
Struts 2 + SpringStruts 2 + Spring
Struts 2 + Spring
 
Painless Persistence with Realm
Painless Persistence with RealmPainless Persistence with Realm
Painless Persistence with Realm
 
Vaadin7
Vaadin7Vaadin7
Vaadin7
 
The State of JavaScript (2015)
The State of JavaScript (2015)The State of JavaScript (2015)
The State of JavaScript (2015)
 
Testing in android
Testing in androidTesting in android
Testing in android
 
RealmDB for Android
RealmDB for AndroidRealmDB for Android
RealmDB for Android
 
Painless Persistence in a Disconnected World
Painless Persistence in a Disconnected WorldPainless Persistence in a Disconnected World
Painless Persistence in a Disconnected World
 
Vaadin 7
Vaadin 7Vaadin 7
Vaadin 7
 
Zendcon 09
Zendcon 09Zendcon 09
Zendcon 09
 
Hi, I need some one to help me with Design a client-server Chat so.pdf
Hi, I need some one to help me with Design a client-server Chat so.pdfHi, I need some one to help me with Design a client-server Chat so.pdf
Hi, I need some one to help me with Design a client-server Chat so.pdf
 
HTML5 for the Silverlight Guy
HTML5 for the Silverlight GuyHTML5 for the Silverlight Guy
HTML5 for the Silverlight Guy
 
Android and the Seven Dwarfs from Devox'15
Android and the Seven Dwarfs from Devox'15Android and the Seven Dwarfs from Devox'15
Android and the Seven Dwarfs from Devox'15
 
Why realm?
Why realm?Why realm?
Why realm?
 
Launching Beeline with Firebase
Launching Beeline with FirebaseLaunching Beeline with Firebase
Launching Beeline with Firebase
 
JavaCro'15 - GWT integration with Vaadin - Peter Lehto
JavaCro'15 - GWT integration with Vaadin - Peter LehtoJavaCro'15 - GWT integration with Vaadin - Peter Lehto
JavaCro'15 - GWT integration with Vaadin - Peter Lehto
 
Addressing Scenario
Addressing ScenarioAddressing Scenario
Addressing Scenario
 

More from Savvycom Savvycom

Vietnam - Asia's newest IT and Outsourcing Tiger
Vietnam - Asia's newest IT and Outsourcing TigerVietnam - Asia's newest IT and Outsourcing Tiger
Vietnam - Asia's newest IT and Outsourcing TigerSavvycom Savvycom
 
Introduction of Big data, NoSQL & Hadoop
Introduction of Big data, NoSQL & HadoopIntroduction of Big data, NoSQL & Hadoop
Introduction of Big data, NoSQL & HadoopSavvycom Savvycom
 
Pros and Cons of Blackberry 10
Pros and Cons of Blackberry 10Pros and Cons of Blackberry 10
Pros and Cons of Blackberry 10Savvycom Savvycom
 
Do's and Don'ts in mobile game development
Do's and Don'ts in mobile game developmentDo's and Don'ts in mobile game development
Do's and Don'ts in mobile game developmentSavvycom Savvycom
 
Trends of Information Technology in 2013
Trends of Information Technology in 2013Trends of Information Technology in 2013
Trends of Information Technology in 2013Savvycom Savvycom
 
Cloud computing - Pros and Cons
Cloud computing - Pros and ConsCloud computing - Pros and Cons
Cloud computing - Pros and ConsSavvycom Savvycom
 
Steps of outsourcing strategy
Steps of outsourcing strategySteps of outsourcing strategy
Steps of outsourcing strategySavvycom Savvycom
 
The role of QR code in daily life
The role of QR code in daily lifeThe role of QR code in daily life
The role of QR code in daily lifeSavvycom Savvycom
 
Why are social games so successful?
Why are social games so successful?Why are social games so successful?
Why are social games so successful?Savvycom Savvycom
 
What makes a complete mobile site
What makes a complete mobile siteWhat makes a complete mobile site
What makes a complete mobile siteSavvycom Savvycom
 

More from Savvycom Savvycom (20)

Serenity-BDD training
Serenity-BDD trainingSerenity-BDD training
Serenity-BDD training
 
Best PHP Framework For 2016
Best PHP Framework For 2016Best PHP Framework For 2016
Best PHP Framework For 2016
 
Vietnam - Asia's newest IT and Outsourcing Tiger
Vietnam - Asia's newest IT and Outsourcing TigerVietnam - Asia's newest IT and Outsourcing Tiger
Vietnam - Asia's newest IT and Outsourcing Tiger
 
Vietnam smartphone usage
Vietnam smartphone usageVietnam smartphone usage
Vietnam smartphone usage
 
Mobile payment
Mobile paymentMobile payment
Mobile payment
 
Introduction of Big data, NoSQL & Hadoop
Introduction of Big data, NoSQL & HadoopIntroduction of Big data, NoSQL & Hadoop
Introduction of Big data, NoSQL & Hadoop
 
Swift Introduction
Swift IntroductionSwift Introduction
Swift Introduction
 
Project manegement
Project manegementProject manegement
Project manegement
 
Business Etiquette Training
Business Etiquette TrainingBusiness Etiquette Training
Business Etiquette Training
 
Pros and Cons of Blackberry 10
Pros and Cons of Blackberry 10Pros and Cons of Blackberry 10
Pros and Cons of Blackberry 10
 
Do's and Don'ts in mobile game development
Do's and Don'ts in mobile game developmentDo's and Don'ts in mobile game development
Do's and Don'ts in mobile game development
 
Trends of Information Technology in 2013
Trends of Information Technology in 2013Trends of Information Technology in 2013
Trends of Information Technology in 2013
 
Cloud computing - Pros and Cons
Cloud computing - Pros and ConsCloud computing - Pros and Cons
Cloud computing - Pros and Cons
 
Steps of outsourcing strategy
Steps of outsourcing strategySteps of outsourcing strategy
Steps of outsourcing strategy
 
Outsourcing to asia
Outsourcing to asiaOutsourcing to asia
Outsourcing to asia
 
The role of QR code in daily life
The role of QR code in daily lifeThe role of QR code in daily life
The role of QR code in daily life
 
Why are social games so successful?
Why are social games so successful?Why are social games so successful?
Why are social games so successful?
 
What makes a complete mobile site
What makes a complete mobile siteWhat makes a complete mobile site
What makes a complete mobile site
 
From app idea to reality
From app idea to realityFrom app idea to reality
From app idea to reality
 
Native app or web app
Native app or web appNative app or web app
Native app or web app
 

Recently uploaded

Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
How to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfHow to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfLivetecs LLC
 
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in NoidaBuds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in Noidabntitsolutionsrishis
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odishasmiwainfosol
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesŁukasz Chruściel
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Natan Silnitsky
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceBrainSell Technologies
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
Best Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfBest Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfIdiosysTechnologies1
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Mater
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationBradBedford3
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Matt Ray
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfMarharyta Nedzelska
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 

Recently uploaded (20)

Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
How to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfHow to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdf
 
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in NoidaBuds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New Features
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. Salesforce
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
Best Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfBest Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdf
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion Application
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdf
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 

Realm Java 2.2.0: Build better apps, faster apps

  • 1. Realm JAVA 2.2.0 Build better apps, faster apps Author: Doi Thanh Thinh Savvycom JSC 1Doi Thanh Thinh - Savvycom JSC
  • 2. SQLite problems • Queries too slow • Complex relationships • Nest SELECT, JOIN • Migration 2Doi Thanh Thinh - Savvycom JSC
  • 3. SQLite problems No-SQL SQLite A B D G C FE Realm.getA().getC().getF(); SELECT user.name, user.email FROM user INNER JOIN shop ON user.id = shop.userid INNER JOIN city ON user.cityid = city.id WHERE user.name = 'the flash' 3Doi Thanh Thinh - Savvycom JSC
  • 4. 1. What Realm Is 2. Compare and contrast with SQLite 3. Implement Realm 4. Example Overview 4Doi Thanh Thinh - Savvycom JSC
  • 5.  Realm is a mobile database and a replacement for SQLite  Core is written in C++  Cross platform mobile database What Realm Is 5Doi Thanh Thinh - Savvycom JSC
  • 6.  Advantages  Faster than SQLite  Support in-memory database  Custom migrating  The Realm file can be stored encrypted on disk by standard AES-256 encryption  Missing Features  Auto-incrementing ids  Compoud primary keys Features 6Doi Thanh Thinh - Savvycom JSC
  • 7. Prerequisites • Do not support Java outside of Android at the moment • Android Studio >= 1.5.1 • A recent version of the Android SDK • JDK version >=7 • Support all Android versions since API Level 9 (Android 2.3 Gingerbread & above) 7Doi Thanh Thinh - Savvycom JSC
  • 8. Benchmarks Faster than SQLite (up to 10x speed up over raw SQLite ) 8Doi Thanh Thinh - Savvycom JSC
  • 11. Step 1: Add the following class path dependency to the project level build.gradle file. buildscript { repositories { jcenter() } dependencies { classpath "io.realm:realm-gradle-plugin:2.2.0" } } Step 2: Apply the realm-android plugin to the top of application level build.gradle file. apply plugin: 'realm-android' Installation 11Doi Thanh Thinh - Savvycom JSC
  • 12.  Models: Realm model classes are created by extending the RealmObject base class. public class User extends RealmObject { private String name; private int age; @Ignore private int sessionId; // Standard getters & setters generated by your IDE… public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public int getSessionId() { return sessionId; } public void setSessionId(int sessionId) { this.sessionId = sessionId; } } Implement Realm Custom methods: public boolean hasLongName() { return name.length() > 7; } 12Doi Thanh Thinh - Savvycom JSC
  • 13.  Field types: Supports the following field types: boolean, byte, short, int, long, float, double, String, Date and byte[]. The boxed types Boolean, Byte, Short, Integer, Long, Float and Double  @Required: used to tell Realm to enforce checks to disallow null values  @Ignore: a field should not be persisted to disk  @PrimaryKey : a primary key field  @Index will add a search index to the field Implement Realm: Types fields 13Doi Thanh Thinh - Savvycom JSC
  • 14. Relationships N – 1 public class Contact extends RealmObject { private Email email; // Other fields… } N - N public class Contact extends RealmObject { public RealmList<Email> emails; // Other fields… } You can use this to model both one-to-many, and many-to-many relationships. 14Doi Thanh Thinh - Savvycom JSC
  • 15. Conditions of Queries  between(), greaterThan(), lessThan(), greaterThanOrEqualTo() & lessThanOrEqualTo()  equalTo() & notEqualTo()  contains(), beginsWith() & endsWith()  isNull() & isNotNull()  isEmpty() & isNotEmpty() 15Doi Thanh Thinh - Savvycom JSC
  • 16. RealmResults<User> r = realm.where(User.class) .greaterThan("age", 10) //implicit AND .beginGroup() .equalTo("name", "Peter") .or() .contains("name", "Jo") .endGroup() .findAll(); Conditions of Queries RealmResults<User> result = realm.where(User.class).findAll(); result = result.sort("age"); // Sort ascending result = result.sort("age", Sort.DESCENDING); 16Doi Thanh Thinh - Savvycom JSC
  • 17. Insert Realm myRealm = Realm.getInstance(this); Person person2 = new Person(); person2.setId("U2"); person2.setName("John"); myRealm.beginTransaction(); // copy the object to realm. Any further changes must happen on realmPerson Person realmPerson = myRealm.copyToRealm(person2); myRealm.commitTransaction(); Dog dog1 = myRealm.createObject(Dog.class); // Set its fields dog1.setId("A"); dog1.setName("Fido"); dog1.setColor("Brown"); myRealm.commitTransaction(); 17Doi Thanh Thinh - Savvycom JSC
  • 18. 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 Auto-Updating Auto Update Realtime 18Doi Thanh Thinh - Savvycom JSC
  • 19. Example public class Person extends RealmObject { private String id; private String name; private RealmList<Dog> dogs; // getters and setters } public class Dog extends RealmObject { private String id; private String name; private String color; // getters and setters } 19Doi Thanh Thinh - Savvycom JSC
  • 20. Example // persons => [U1,U2] RealmResults<Person> persons = realm.where(Person.class) .equalTo("dogs.color", "Brown") .findAll(); // r1 => [U1,U2] RealmResults<Person> r1 = realm.where(Person.class) .equalTo("dogs.name", "Fluffy") .equalTo("dogs.color", "Brown") .findAll(); // r2 => [U2] RealmResults<Person> r2 = realm.where(Person.class) .equalTo("dogs.name", "Fluffy") .findAll() .where() .equalTo("dogs.color", "Brown") .findAll(); .where() .equalTo("dogs.color", "Yellow") .findAll(); 20Doi Thanh Thinh - Savvycom JSC
  • 21. Insert/Update Asynchronous Transactions: 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. } }); Avoid blocking the UI thread 21Doi Thanh Thinh - Savvycom JSC
  • 22. Delete // obtain the results of a query final 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) { // remove single match results.deleteFirstFromRealm(); results.deleteLastFromRealm(); // remove a single object Dog dog = results.get(5); dog.deleteFromRealm(); // Delete all matches results.deleteAllFromRealm(); } }); 22Doi Thanh Thinh - Savvycom JSC
  • 23. JSON • It is possible to add RealmObjects represented as JSON directly to Realm . they are represented as a String, a JSONObject or an InputStream • Single object is added through Realm.createObjectFromJson() • lists of objects are added using Realm.createAllFromJson(). // A RealmObject that represents a city public class City extends RealmObject { private String city; private int id; // getters and setters left out ... } // Insert from a string realm.executeTransaction(new Realm.Transaction() { @Override public void execute(Realm realm) { realm.createObjectFromJson(City.class, "{ city: "Copenhagen", id: 1 }"); } }); 23Doi Thanh Thinh - Savvycom JSC
  • 24. Demo 24Doi Thanh Thinh - Savvycom JSC
  • 25. Resources Official Site for Realm https://realm.io/ Realm Full API for Java http://realm.io/docs/java/latest/api/ Realm Browser: https://github.com/realm/realm-cocoa/tree/master/tools/RealmBrowser Github: https://github.com/thinhdt/DemoRealm 25Doi Thanh Thinh - Savvycom JSC