SlideShare a Scribd company logo
1 of 25
Realm JAVA 2.2.0
Build better apps, faster.
Author: Đới Thanh Thịnh
Savvycom-software
SQLite problems
• Queries too slow
• Complex
relationships
• Nest SELECT, JOIN
• Migration
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'
1. What Realm Is
2. Compare and contrast with SQLite
3. Implement Realm
4. Example
Overview
 Realm is a mobile database and a replacement for
SQLite
 Core is written in C++
 Cross platform mobile database
What Realm Is
 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
Prerequisites
We 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.
We support all Android versions since API Level 9 (Android 2.3
Gingerbread & above).
Benchmarks
Faster than SQLite (up to 10x speed up over raw SQLite )
Benchmarks
Benchmarks
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
 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;
}
 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
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.
Conditions of Queries
 between(), greaterThan(), lessThan(), greaterThanOrEqualTo() &
lessThanOrEqualTo()
 equalTo() & notEqualTo()
 contains(), beginsWith() & endsWith()
 isNull() & isNotNull()
 isEmpty() & isNotEmpty()
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);
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();
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
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
}
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")
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
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();
}
});
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 }");
}
});
Demo
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

More Related Content

What's hot

Designing with Groovy Traits - Gr8Conf India
Designing with Groovy Traits - Gr8Conf IndiaDesigning with Groovy Traits - Gr8Conf India
Designing with Groovy Traits - Gr8Conf IndiaNaresha K
 
Zend Framework 1 + Doctrine 2
Zend Framework 1 + Doctrine 2Zend Framework 1 + Doctrine 2
Zend Framework 1 + Doctrine 2Ralph Schindler
 
Semantic code transformations in MetaJS
Semantic code transformations in MetaJSSemantic code transformations in MetaJS
Semantic code transformations in MetaJSDmytro Dogadailo
 
The art of readable code (ch1~ch4)
The art of readable code (ch1~ch4)The art of readable code (ch1~ch4)
The art of readable code (ch1~ch4)Ki Sung Bae
 
Using Xcore with Xtext
Using Xcore with XtextUsing Xcore with Xtext
Using Xcore with XtextHolger Schill
 
iPhone Development Intro
iPhone Development IntroiPhone Development Intro
iPhone Development IntroLuis Azevedo
 
G3 Summit 2016 - Taking Advantage of Groovy Annotations
G3 Summit 2016 - Taking Advantage of Groovy AnnotationsG3 Summit 2016 - Taking Advantage of Groovy Annotations
G3 Summit 2016 - Taking Advantage of Groovy AnnotationsIván López Martín
 
Madrid gug - sacando partido a las transformaciones ast de groovy
Madrid gug - sacando partido a las transformaciones ast de groovyMadrid gug - sacando partido a las transformaciones ast de groovy
Madrid gug - sacando partido a las transformaciones ast de groovyIván López Martín
 
ElasticSearch 5.x - New Tricks - 2017-02-08 - Elasticsearch Meetup
ElasticSearch 5.x -  New Tricks - 2017-02-08 - Elasticsearch Meetup ElasticSearch 5.x -  New Tricks - 2017-02-08 - Elasticsearch Meetup
ElasticSearch 5.x - New Tricks - 2017-02-08 - Elasticsearch Meetup Alberto Paro
 
The Art Of Readable Code
The Art Of Readable CodeThe Art Of Readable Code
The Art Of Readable CodeBaidu, Inc.
 
Ruby and rails - Advanced Training (Cybage)
Ruby and rails - Advanced Training (Cybage)Ruby and rails - Advanced Training (Cybage)
Ruby and rails - Advanced Training (Cybage)Gautam Rege
 
Kotlin – the future of android
Kotlin – the future of androidKotlin – the future of android
Kotlin – the future of androidDJ Rausch
 
Scala at HUJI PL Seminar 2008
Scala at HUJI PL Seminar 2008Scala at HUJI PL Seminar 2008
Scala at HUJI PL Seminar 2008Yardena Meymann
 
concurrency with GPars
concurrency with GParsconcurrency with GPars
concurrency with GParsPaul King
 
Clojure Intro
Clojure IntroClojure Intro
Clojure Introthnetos
 
Building High Performance Web Applications and Sites
Building High Performance Web Applications and SitesBuilding High Performance Web Applications and Sites
Building High Performance Web Applications and Sitesgoodfriday
 

What's hot (20)

Designing with Groovy Traits - Gr8Conf India
Designing with Groovy Traits - Gr8Conf IndiaDesigning with Groovy Traits - Gr8Conf India
Designing with Groovy Traits - Gr8Conf India
 
Zend Framework 1 + Doctrine 2
Zend Framework 1 + Doctrine 2Zend Framework 1 + Doctrine 2
Zend Framework 1 + Doctrine 2
 
Semantic code transformations in MetaJS
Semantic code transformations in MetaJSSemantic code transformations in MetaJS
Semantic code transformations in MetaJS
 
The art of readable code (ch1~ch4)
The art of readable code (ch1~ch4)The art of readable code (ch1~ch4)
The art of readable code (ch1~ch4)
 
Using Xcore with Xtext
Using Xcore with XtextUsing Xcore with Xtext
Using Xcore with Xtext
 
iPhone Development Intro
iPhone Development IntroiPhone Development Intro
iPhone Development Intro
 
G3 Summit 2016 - Taking Advantage of Groovy Annotations
G3 Summit 2016 - Taking Advantage of Groovy AnnotationsG3 Summit 2016 - Taking Advantage of Groovy Annotations
G3 Summit 2016 - Taking Advantage of Groovy Annotations
 
Madrid gug - sacando partido a las transformaciones ast de groovy
Madrid gug - sacando partido a las transformaciones ast de groovyMadrid gug - sacando partido a las transformaciones ast de groovy
Madrid gug - sacando partido a las transformaciones ast de groovy
 
Java for beginners
Java for beginnersJava for beginners
Java for beginners
 
SOLID Ruby, SOLID Rails
SOLID Ruby, SOLID RailsSOLID Ruby, SOLID Rails
SOLID Ruby, SOLID Rails
 
ElasticSearch 5.x - New Tricks - 2017-02-08 - Elasticsearch Meetup
ElasticSearch 5.x -  New Tricks - 2017-02-08 - Elasticsearch Meetup ElasticSearch 5.x -  New Tricks - 2017-02-08 - Elasticsearch Meetup
ElasticSearch 5.x - New Tricks - 2017-02-08 - Elasticsearch Meetup
 
The Art Of Readable Code
The Art Of Readable CodeThe Art Of Readable Code
The Art Of Readable Code
 
Django - sql alchemy - jquery
Django - sql alchemy - jqueryDjango - sql alchemy - jquery
Django - sql alchemy - jquery
 
Ruby and rails - Advanced Training (Cybage)
Ruby and rails - Advanced Training (Cybage)Ruby and rails - Advanced Training (Cybage)
Ruby and rails - Advanced Training (Cybage)
 
Kotlin – the future of android
Kotlin – the future of androidKotlin – the future of android
Kotlin – the future of android
 
Scala at HUJI PL Seminar 2008
Scala at HUJI PL Seminar 2008Scala at HUJI PL Seminar 2008
Scala at HUJI PL Seminar 2008
 
concurrency with GPars
concurrency with GParsconcurrency with GPars
concurrency with GPars
 
OO in JavaScript
OO in JavaScriptOO in JavaScript
OO in JavaScript
 
Clojure Intro
Clojure IntroClojure Intro
Clojure Intro
 
Building High Performance Web Applications and Sites
Building High Performance Web Applications and SitesBuilding High Performance Web Applications and Sites
Building High Performance Web Applications and Sites
 

Viewers also liked

La biblioteca accademica nella filiera della comunicazione scientifica: ridef...
La biblioteca accademica nella filiera della comunicazione scientifica: ridef...La biblioteca accademica nella filiera della comunicazione scientifica: ridef...
La biblioteca accademica nella filiera della comunicazione scientifica: ridef...Università di Padova
 
16. Vías respiratorias
16. Vías respiratorias16. Vías respiratorias
16. Vías respiratoriasEmagister
 
итоговая коллегия
итоговая коллегия итоговая коллегия
итоговая коллегия sk1ll
 
124I & 89Zr Radiopharmaceuticals as an Alternative to F-18 Tracers – a Compar...
124I & 89Zr Radiopharmaceuticals as an Alternative to F-18 Tracers – a Compar...124I & 89Zr Radiopharmaceuticals as an Alternative to F-18 Tracers – a Compar...
124I & 89Zr Radiopharmaceuticals as an Alternative to F-18 Tracers – a Compar...Soppata
 
Jenkins + Pipeline Plugin + Docker
Jenkins + Pipeline Plugin + DockerJenkins + Pipeline Plugin + Docker
Jenkins + Pipeline Plugin + Dockertak-nakamura
 
Le mille e una aspettativa: i bibliotecari pubblici di fronte al mondo che ca...
Le mille e una aspettativa: i bibliotecari pubblici di fronte al mondo che ca...Le mille e una aspettativa: i bibliotecari pubblici di fronte al mondo che ca...
Le mille e una aspettativa: i bibliotecari pubblici di fronte al mondo che ca...Anna Galluzzi
 
Draft Raperbup penilaian dokumen lingkungan dan izin lingkungan kabupaten ban...
Draft Raperbup penilaian dokumen lingkungan dan izin lingkungan kabupaten ban...Draft Raperbup penilaian dokumen lingkungan dan izin lingkungan kabupaten ban...
Draft Raperbup penilaian dokumen lingkungan dan izin lingkungan kabupaten ban...Dianora Didi
 
魅せるPPT基本編
魅せるPPT基本編魅せるPPT基本編
魅せるPPT基本編nkanazawa
 
JT's General Resume 2016
JT's General Resume 2016JT's General Resume 2016
JT's General Resume 2016James Hankins
 
ソフトウェアテスト入門
ソフトウェアテスト入門ソフトウェアテスト入門
ソフトウェアテスト入門iKenji
 

Viewers also liked (14)

La biblioteca accademica nella filiera della comunicazione scientifica: ridef...
La biblioteca accademica nella filiera della comunicazione scientifica: ridef...La biblioteca accademica nella filiera della comunicazione scientifica: ridef...
La biblioteca accademica nella filiera della comunicazione scientifica: ridef...
 
16. Vías respiratorias
16. Vías respiratorias16. Vías respiratorias
16. Vías respiratorias
 
Listening skills
Listening skillsListening skills
Listening skills
 
итоговая коллегия
итоговая коллегия итоговая коллегия
итоговая коллегия
 
124I & 89Zr Radiopharmaceuticals as an Alternative to F-18 Tracers – a Compar...
124I & 89Zr Radiopharmaceuticals as an Alternative to F-18 Tracers – a Compar...124I & 89Zr Radiopharmaceuticals as an Alternative to F-18 Tracers – a Compar...
124I & 89Zr Radiopharmaceuticals as an Alternative to F-18 Tracers – a Compar...
 
Jenkins + Pipeline Plugin + Docker
Jenkins + Pipeline Plugin + DockerJenkins + Pipeline Plugin + Docker
Jenkins + Pipeline Plugin + Docker
 
Le mille e una aspettativa: i bibliotecari pubblici di fronte al mondo che ca...
Le mille e una aspettativa: i bibliotecari pubblici di fronte al mondo che ca...Le mille e una aspettativa: i bibliotecari pubblici di fronte al mondo che ca...
Le mille e una aspettativa: i bibliotecari pubblici di fronte al mondo che ca...
 
Draft Raperbup penilaian dokumen lingkungan dan izin lingkungan kabupaten ban...
Draft Raperbup penilaian dokumen lingkungan dan izin lingkungan kabupaten ban...Draft Raperbup penilaian dokumen lingkungan dan izin lingkungan kabupaten ban...
Draft Raperbup penilaian dokumen lingkungan dan izin lingkungan kabupaten ban...
 
魅せるPPT基本編
魅せるPPT基本編魅せるPPT基本編
魅せるPPT基本編
 
Whats_your_identity
Whats_your_identityWhats_your_identity
Whats_your_identity
 
ehab
ehabehab
ehab
 
JT's General Resume 2016
JT's General Resume 2016JT's General Resume 2016
JT's General Resume 2016
 
ソフトウェアテスト入門
ソフトウェアテスト入門ソフトウェアテスト入門
ソフトウェアテスト入門
 
Ariosto
AriostoAriosto
Ariosto
 

Similar to Present realm

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 appsSavvycom Savvycom
 
Addressing Scenario
Addressing ScenarioAddressing Scenario
Addressing ScenarioTara Hardin
 
Painless Persistence in a Disconnected World
Painless Persistence in a Disconnected WorldPainless Persistence in a Disconnected World
Painless Persistence in a Disconnected WorldChristian Melchior
 
Scala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghScala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghStuart Roebuck
 
14. Defining Classes
14. Defining Classes14. Defining Classes
14. Defining ClassesIntro C# Book
 
2017 02-07 - elastic & spark. building a search geo locator
2017 02-07 - elastic & spark. building a search geo locator2017 02-07 - elastic & spark. building a search geo locator
2017 02-07 - elastic & spark. building a search geo locatorAlberto Paro
 
2017 02-07 - elastic & spark. building a search geo locator
2017 02-07 - elastic & spark. building a search geo locator2017 02-07 - elastic & spark. building a search geo locator
2017 02-07 - elastic & spark. building a search geo locatorAlberto Paro
 
CSharp presentation and software developement
CSharp presentation and software developementCSharp presentation and software developement
CSharp presentation and software developementfrwebhelp
 
Easy data-with-spring-data-jpa
Easy data-with-spring-data-jpaEasy data-with-spring-data-jpa
Easy data-with-spring-data-jpaStaples
 
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
 
Building a friendly .NET SDK to connect to Space
Building a friendly .NET SDK to connect to SpaceBuilding a friendly .NET SDK to connect to Space
Building a friendly .NET SDK to connect to SpaceMaarten Balliauw
 
the next web now
the next web nowthe next web now
the next web nowzulin Gu
 

Similar to Present realm (20)

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
 
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
 
Addressing Scenario
Addressing ScenarioAddressing Scenario
Addressing Scenario
 
Painless Persistence in a Disconnected World
Painless Persistence in a Disconnected WorldPainless Persistence in a Disconnected World
Painless Persistence in a Disconnected World
 
Scala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghScala @ TechMeetup Edinburgh
Scala @ TechMeetup Edinburgh
 
14. Defining Classes
14. Defining Classes14. Defining Classes
14. Defining Classes
 
2017 02-07 - elastic & spark. building a search geo locator
2017 02-07 - elastic & spark. building a search geo locator2017 02-07 - elastic & spark. building a search geo locator
2017 02-07 - elastic & spark. building a search geo locator
 
2017 02-07 - elastic & spark. building a search geo locator
2017 02-07 - elastic & spark. building a search geo locator2017 02-07 - elastic & spark. building a search geo locator
2017 02-07 - elastic & spark. building a search geo locator
 
CSharp presentation and software developement
CSharp presentation and software developementCSharp presentation and software developement
CSharp presentation and software developement
 
Easy data-with-spring-data-jpa
Easy data-with-spring-data-jpaEasy data-with-spring-data-jpa
Easy data-with-spring-data-jpa
 
Clean Code 2
Clean Code 2Clean Code 2
Clean Code 2
 
Realm mobile database
Realm mobile databaseRealm mobile database
Realm mobile database
 
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
 
Realm database
Realm databaseRealm database
Realm database
 
TechTalk - Dotnet
TechTalk - DotnetTechTalk - Dotnet
TechTalk - Dotnet
 
.NET Reflection
.NET Reflection.NET Reflection
.NET Reflection
 
Building a friendly .NET SDK to connect to Space
Building a friendly .NET SDK to connect to SpaceBuilding a friendly .NET SDK to connect to Space
Building a friendly .NET SDK to connect to Space
 
Slickdemo
SlickdemoSlickdemo
Slickdemo
 
RealmDB for Android
RealmDB for AndroidRealmDB for Android
RealmDB for Android
 
the next web now
the next web nowthe next web now
the next web now
 

Present realm

  • 1. Realm JAVA 2.2.0 Build better apps, faster. Author: Đới Thanh Thịnh Savvycom-software
  • 2. SQLite problems • Queries too slow • Complex relationships • Nest SELECT, JOIN • Migration
  • 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'
  • 4. 1. What Realm Is 2. Compare and contrast with SQLite 3. Implement Realm 4. Example Overview
  • 5.  Realm is a mobile database and a replacement for SQLite  Core is written in C++  Cross platform mobile database What Realm Is
  • 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
  • 7. Prerequisites We 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. We support all Android versions since API Level 9 (Android 2.3 Gingerbread & above).
  • 8. Benchmarks Faster than SQLite (up to 10x speed up over raw SQLite )
  • 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
  • 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; }
  • 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
  • 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.
  • 15. Conditions of Queries  between(), greaterThan(), lessThan(), greaterThanOrEqualTo() & lessThanOrEqualTo()  equalTo() & notEqualTo()  contains(), beginsWith() & endsWith()  isNull() & isNotNull()  isEmpty() & isNotEmpty()
  • 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);
  • 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();
  • 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
  • 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 }
  • 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")
  • 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
  • 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(); } });
  • 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 }"); } });
  • 24. Demo
  • 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

Editor's Notes

  1. RealmList is used to model one-to-many relationships in a RealmObject. RealmResults are always the result of a database query. RealmList can be used inside of a RealmObject to define One-To-Many relationships (RealmResults can't).
  2. https://realm.io/news/realm-for-android/#inserts
  3. - A Realm model class also supports public, protected and private fields as well as custom methods.
  4. The integer types byte, short, int, and long are all mapped to the same type (long actually)
  5. You can establish a relationship to any number of objects from a single object via a RealmList<T> field declaration. RealmLists are basically containers of RealmObjects - using the same email object in multiple contacts, - N- N: you can use this to model both one-to-many, and many-to-many relationships.
  6. Modifying objects that affect the query will be reflected in the results immediately.
  7. As transactions are blocked by other transactions it can be an advantage to do all writes on a background thread in order to avoid blocking the UI thread. RealmResults<User> result = realm.where(User.class) .equalTo("name", "John") .or() .equalTo("name", "Peter") .findAllAsync();
  8. Realm will ignore any properties in the JSON not defined by the RealmObject For a not-required field, set it to null which is the default value. For a required field, throw an exception.