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

PDF
Natural Language Toolkit (NLTK), Basics
PDF
The Ring programming language version 1.5.2 book - Part 6 of 181
KEY
NLTK in 20 minutes
PDF
David Kopal - Unleash the power of the higher-order components
PDF
Using Combine, SwiftUI and callAsFunction to build an experimental localizati...
PDF
The Xtext Grammar Language
PPSX
Spring has got me under it’s SpEL
PDF
Text analysis using python
Natural Language Toolkit (NLTK), Basics
The Ring programming language version 1.5.2 book - Part 6 of 181
NLTK in 20 minutes
David Kopal - Unleash the power of the higher-order components
Using Combine, SwiftUI and callAsFunction to build an experimental localizati...
The Xtext Grammar Language
Spring has got me under it’s SpEL
Text analysis using python

What's hot (20)

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

Viewers also liked (14)

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

Similar to Present realm (20)

PDF
Realm Java 2.2.0: Build better apps, faster apps
PDF
Realm Java 2.2.0: Build better apps, faster apps
PPTX
RealmDB for Android
ODP
Realm Mobile Database - An Introduction
PPTX
Realm mobile database
PDF
Painless Persistence in a Disconnected World
PDF
No sql databases blrdroid devfest 2016
PDF
#MBLTdev: Уроки, которые мы выучили, создавая Realm
PPTX
Realm database
PPTX
Realm or: How I learned to stop worrying and love my app database
PDF
PDF
Realm: Building a mobile database
PDF
Painless Persistence with Realm
PDF
Realm Presentation
PDF
MongoDB .local Bengaluru 2019: Realm: The Secret Sauce for Better Mobile Apps
PDF
Realm of the Mobile Database: an introduction to Realm
PPTX
Realm Java for Android
PDF
React-Native Lecture 11: In App Storage
PDF
PDF
Убийца SQLite, или Мобильная БД с блек-джеком и синхронизацией
Realm Java 2.2.0: Build better apps, faster apps
Realm Java 2.2.0: Build better apps, faster apps
RealmDB for Android
Realm Mobile Database - An Introduction
Realm mobile database
Painless Persistence in a Disconnected World
No sql databases blrdroid devfest 2016
#MBLTdev: Уроки, которые мы выучили, создавая Realm
Realm database
Realm or: How I learned to stop worrying and love my app database
Realm: Building a mobile database
Painless Persistence with Realm
Realm Presentation
MongoDB .local Bengaluru 2019: Realm: The Secret Sauce for Better Mobile Apps
Realm of the Mobile Database: an introduction to Realm
Realm Java for Android
React-Native Lecture 11: In App Storage
Убийца SQLite, или Мобильная БД с блек-джеком и синхронизацией

Recently uploaded (8)

DOC
EIU毕业证学历认证,贝尔维尤学院毕业证国外毕业证
PDF
Top 10 Platforms for Securely Buying Verified Cash App Accounts.pdf
PDF
2025 Guide to Buy Verified Cash App Accounts You Can Trust.pdf
PDF
Date Right Stuff - Invite only, conservative dating app
PDF
Kids, Screens & Emotional Development by Meenakshi Khakat
PDF
Best 4 Sites for Buy Verified Cash App Accounts – BTC Only.pdf
PPTX
The-Literary-Elements in non fiction creative
PPTX
Social Media People PowerPoint Templates.pptx
EIU毕业证学历认证,贝尔维尤学院毕业证国外毕业证
Top 10 Platforms for Securely Buying Verified Cash App Accounts.pdf
2025 Guide to Buy Verified Cash App Accounts You Can Trust.pdf
Date Right Stuff - Invite only, conservative dating app
Kids, Screens & Emotional Development by Meenakshi Khakat
Best 4 Sites for Buy Verified Cash App Accounts – BTC Only.pdf
The-Literary-Elements in non fiction creative
Social Media People PowerPoint Templates.pptx

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

  • #2: 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).
  • #9: https://realm.io/news/realm-for-android/#inserts
  • #13: - A Realm model class also supports public, protected and private fields as well as custom methods.
  • #14: The integer types byte, short, int, and long are all mapped to the same type (long actually)
  • #15: 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.
  • #19: Modifying objects that affect the query will be reflected in the results immediately.
  • #22: 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();
  • #24: 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.