SlideShare a Scribd company logo
RealmDB. Fast & Simple
by Anton Minashkin
Whats wrong with SQLite + ORM?
● Boilerplate code
● SQL is ugly and hard to learn
● DTO <-> ORM
● Threads
Realm is a mobile
database
Realm is a replacement for SQLite & Core Data.
It can save you thousands of lines of code & weeks of work,
and lets you craft amazing new user experiences.
Realm is…
blah-blah-blah…
...fast and simple data
storage
...and cute ^_^
History
● Comes from YCombinator
● TightDB -> Realm
● In development since 2011
● 2nd-most deployed DB in the world (proof?)
Fast
Fast
Fast
Why so fast?
● zero-copy architecture
● bitpacking reduces memory usage by up to
90%
● caching & vectorization makes access faster
then native C
● built from scratch, based on C++ core
● proxy
Models
Field types: boolean, short, ìnt, long, float, double,
String, Date and byte[]
Annotations: @Ignore, @Index, @PrimaryKey
Models
public class User extends RealmObject {
@PrimaryKey
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 dontPersist) { this.sessionId = sessionId; }
}
Writes
● Always use Transactions
● Writes block each other
● Use Realm.copyToRealm()
● Read & Writes are ACID
Creating objects
realm.beginTransaction();
User user = realm.createObject(User.class);
user.setName("John");
user.setEmail("john@corporation.com");
realm.commitTransaction();
Creating objects
User user = new User("John");
user.setEmail("john@corporation.com");
realm.beginTransaction();
User realmUser = realm.copyToRealm(user);
realm.commitTransaction();
Transaction blocks
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");
}
});
Queries
// Build the query looking at all users:
RealmQuery<User> query = realm.where(User.class);
// Add query conditions:
query.equalTo("name", "John");
query.or().equalTo("name", "Peter");
// Execute the query:
RealmResults<User> result1 = query.findAll();
Queries
RealmResults<User> result = realm.where(User.class)
.equalTo("name", "John")
.or()
.equalTo("name", "Peter")
.findAll();
Retrieving objects by type
Realm.allObjects(java.lang.Class<E> clazz)
Realm.allObjectsSorted(...)
Conditions
● between, greaterThan(), lessThan(), greaterThanOrEqualTo() &
lessThanOrEqualTo()
● equalTo() & notEqualTo()
● contains(), beginsWith() & endsWith()
Modifiers
String conditions can ignore case for characters
A-Z and a-z by using the CASE_INSENSITIVE
modifier.
Implicit Logical Operators
RealmResults<User> r = realm.where(User.class)
.greaterThan("age", 10) //AND
.beginGroup()
.equalTo("name", "Peter")
.or()
.contains("name", "Jo")
.endGroup()
.findAll();
Sorting
RealmResults<User> result = realm.where(User.class).findAll();
result.sort("age"); // Sort ascending
result.sort("age", RealmResults.SORT_ORDER_DESCENDING);
Chaining Queries
RealmResults<User> teenagers = realm.where(User.class)
.between("age", 13, 20).findAll();
RealmResults<User> firstJohn = teenagers.where().equalTo("name",
"John").findFirst();
Aggregation
long sum = result.sum("age").longValue();
long min = result.min("age").longValue();
long max = result.max("age").longValue();
double average = result.average("age");
long matches = result.size();
Iterations
for (User u : result) {
// ... do something with the object ...
}
for (int i = 0; i < result.size(); i++) {
User u = result.get(i);
// ... do something with the object ...
}
Deletion
// All changes to data must happen in a transaction
realm.beginTransaction();
// remove single match
result.remove(0);
result.removeLast();
// remove a single object
Dog dog = result.get(5);
dog.removeFromRealm();
// Delete all matches
result.clear();
realm.commitTransaction()
Realms
Realm == Database
The Default Realm
Realm.getInstance(Context context)
Mapped to: default.realm
Located in: Context.getFilesDir() --/data/data/files/
Check location: realm.getPath()
Other Realms
Realm realm = Realm.getInstance(this, "mycustom.realm");
Using a Realm across Threads
Realm, RealmObject or RealmResults instances cannot be passed across
threads!
Wanna same objects in other thread? Requery!
Closing Realm instances
Realm implements Closeable
Realm instances are reference counted
For the UI thread the easiest way is to execute realm.close() in the
onDestroy() method.
Auto-Refresh
If a thread is associated with Looper (e.g. UI thread) then Realm has
AutoRefresh feature;
Check it: Realm.isAutoRefresh()
Relationships
public class Email extends RealmObject {
private String address;
private boolean active;
// ... setters and getters left out
}
public class Contact extends RealmObject {
private String name;
private Email email;
// ... setters and getters left out
}
Relationships
public class Contact extends RealmObject {
private RealmList<Email> emails;
// Other fields…
}
RealmResults<Contact> contacts = realm
.where(Contact.class)
.equalTo("email.active", true).findAll();
JSON
Object should be represented as: String, JSONObject, InputStream
// Insert from a string
realm.beginTransaction();
realm.createObjectFromJson(City.class, "{ city: "Copenhagen",
id: 1 }");
realm.commitTransaction();
JSON
// Insert multiple items using a InputStream
InputStream is = new FileInputStream(new File("path_to_file"));
realm.beginTransaction();
try {
realm.createAllFromJson(City.class, is);
realm.commitTransaction();
} catch (IOException e) {
realm.cancelTransaction();
}
Notifications
realm.addChangeListener(new RealmChangeListener() {
@Override
public void onChange() {
// ... do something with the updates (UI, etc.) ...
}
});
…
realm.removeAllChangeListeners();
Migrations
Migrations are a work in progress. The feature is fully functional, but the current
interface is cumbersome, and will be rewritten soon.
Encryption
Please take note of the Export Compliance section of our LICENSE, as it
places restrictions against the usage of Realm if you are located in countries
with an export restriction or embargo from the United States.
Encryption
byte[] key = new byte[32];
new SecureRandom().nextBytes(key);
Realm realm = Realm.create(this, key);
// ... use the Realm as normal ...
Encryption
Using Encryption requires building Realm from source:
1. Follow the normal build instructions, but before running ./gradlew
assemble, add the lineencryption=true to local.properties.
2. After building Realm, replace the copy of realm-<VERSION>.aar in your
project with the one found at realm/build/outputs/aar/realm-
<VERSION>.aar.
Adapter
public class MyAdapter extends RealmBaseAdapter<TimeStamp>
implements ListAdapter {
…
@Override
public View getView(int position, View convertView,
ViewGroup parent) {...}
}
Realm Browser
Realm Browser
Only available on Mac OS X at the moment! We are working on Windows &
Linux versions.
Example
Code time!
Current limitations (still beta)
General:
1. The upper limit of class names is 57 characters. Realm for Android prepend class_ to all names,
and the browser will show it as part of the name.
2. The length of field names has a upper limit of 63 character.
3. The dates are truncated with a precision of one second. In order to maintain compability
between 32 bits and 64 bits devices, it is not possible to store dates before 1900-12-13 and after
2038-01-19.
Current limitations (still beta)
General:
4. Nested transactions are not supported, and an exception is throw if it is detected.
5. Strings and byte arrays (byte[]) cannot be larger than 16 MB.
6. Case insensitive string matches in queries are only supported for character sets in ‘Latin Basic’,
‘Latin Supplement’, ‘Latin Extended A’, ‘Latin Extended B’ (UTF-8 range 0-591).
Current limitations (still beta)
Sorting
Sorting is currently limited to character sets in ‘Latin Basic’, ‘Latin Supplement’, ‘Latin Extended A’,
‘Latin Extended B’ (UTF-8 range 0-591). For other charsets, sorting will not change the RealmResults
object.
Current limitations (still beta)
Threads
Although Realm files can be accessed by multiple threads concurrently, you cannot hand over
Realms, Realm objects, queries, and results between threads. Moreover, asynchronous queries are
currently not supported.
Current limitations (still beta)
null values
It is not possible to store null as a value for primitive data types (booleans, integers, floating-point
numbers, dates, and strings). Supporting null is under active development but until fully supported, we
suggest that you add an extra boolean field to capture if a field is null or not.
Current limitations (still beta)
Realm files cannot be accessed by concurrent processes
Although Realm files can be accessed by multiple threads concurrently, they can only be accessed by
a single process at a time. Different processes should either copy Realm files or create their own.
Multi-process support is coming soon.
Questions?
Thanks =)
http://realm.io/
http://realm.io/docs/java/0.80.0/
@Twitter: AntonMinashkin
Email: anton.minashkin@outlook.com

More Related Content

PPTX
Nicety of Java 8 Multithreading
GlobalLogic Ukraine
 
PDF
The Ring programming language version 1.3 book - Part 84 of 88
Mahmoud Samir Fayed
 
PDF
Memory management
Kuban Dzhakipov
 
PPT
JVM performance options. How it works
Dmitriy Dumanskiy
 
PDF
Collections forceawakens
RichardWarburton
 
PDF
Handling 20 billion requests a month
Dmitriy Dumanskiy
 
PDF
Tweaking performance on high-load projects
Dmitriy Dumanskiy
 
PDF
Engineering fast indexes (Deepdive)
Daniel Lemire
 
Nicety of Java 8 Multithreading
GlobalLogic Ukraine
 
The Ring programming language version 1.3 book - Part 84 of 88
Mahmoud Samir Fayed
 
Memory management
Kuban Dzhakipov
 
JVM performance options. How it works
Dmitriy Dumanskiy
 
Collections forceawakens
RichardWarburton
 
Handling 20 billion requests a month
Dmitriy Dumanskiy
 
Tweaking performance on high-load projects
Dmitriy Dumanskiy
 
Engineering fast indexes (Deepdive)
Daniel Lemire
 

What's hot (20)

PPT
20100712-OTcl Command -- Getting Started
Teerawat Issariyakul
 
PDF
Full Stack Clojure
Michiel Borkent
 
PDF
The Ring programming language version 1.10 book - Part 22 of 212
Mahmoud Samir Fayed
 
PDF
Out ofmemoryerror what is the cost of java objects
Jean-Philippe BEMPEL
 
PPT
NS2 Object Construction
Teerawat Issariyakul
 
ODP
AST Transformations at JFokus
HamletDRC
 
PDF
Java Concurrency Idioms
Alex Miller
 
PDF
DConf 2016: Keynote by Walter Bright
Andrei Alexandrescu
 
PPTX
Codable routing
Pushkar Kulkarni
 
PDF
ClojureScript for the web
Michiel Borkent
 
PDF
Hw09 Hadoop + Clojure
Cloudera, Inc.
 
PPTX
Kotlin – the future of android
DJ Rausch
 
PDF
Dynamic C++ ACCU 2013
aleks-f
 
ODP
Meetup slides
suraj_atreya
 
PDF
ClojureScript loves React, DomCode May 26 2015
Michiel Borkent
 
PPTX
New Indexing and Aggregation Pipeline Capabilities in MongoDB 4.2
Antonios Giannopoulos
 
PPTX
Scala
suraj_atreya
 
PDF
ooc - OSDC 2010 - Amos Wenger
Amos Wenger
 
PDF
Java Concurrency Gotchas
Alex Miller
 
PDF
Hadoop + Clojure
elliando dias
 
20100712-OTcl Command -- Getting Started
Teerawat Issariyakul
 
Full Stack Clojure
Michiel Borkent
 
The Ring programming language version 1.10 book - Part 22 of 212
Mahmoud Samir Fayed
 
Out ofmemoryerror what is the cost of java objects
Jean-Philippe BEMPEL
 
NS2 Object Construction
Teerawat Issariyakul
 
AST Transformations at JFokus
HamletDRC
 
Java Concurrency Idioms
Alex Miller
 
DConf 2016: Keynote by Walter Bright
Andrei Alexandrescu
 
Codable routing
Pushkar Kulkarni
 
ClojureScript for the web
Michiel Borkent
 
Hw09 Hadoop + Clojure
Cloudera, Inc.
 
Kotlin – the future of android
DJ Rausch
 
Dynamic C++ ACCU 2013
aleks-f
 
Meetup slides
suraj_atreya
 
ClojureScript loves React, DomCode May 26 2015
Michiel Borkent
 
New Indexing and Aggregation Pipeline Capabilities in MongoDB 4.2
Antonios Giannopoulos
 
ooc - OSDC 2010 - Amos Wenger
Amos Wenger
 
Java Concurrency Gotchas
Alex Miller
 
Hadoop + Clojure
elliando dias
 
Ad

Similar to RealmDB for Android (20)

PPT
Real World Experience With Oracle Xml Database 11g An Oracle Ace’s Perspectiv...
Marco Gralike
 
PPTX
NoSQL Endgame DevoxxUA Conference 2020
Thodoris Bais
 
PPTX
NoSQL Endgame - Java2Days 2020 Virtual
Werner Keil
 
PDF
Http4s, Doobie and Circe: The Functional Web Stack
GaryCoady
 
PDF
Realm of the Mobile Database: an introduction to Realm
Martin Grider
 
PDF
Coding Ajax
Ted Husted
 
PDF
Realm Java 2.2.0: Build better apps, faster apps
Savvycom - Software Product Development
 
PDF
Realm Java 2.2.0: Build better apps, faster apps
Savvycom Savvycom
 
PDF
Kotlin for Android Development
Speck&Tech
 
PPTX
Art of Javascript
Tarek Yehia
 
PPTX
Boosting performance and functional style with Project Arrow from a practical...
João Esperancinha
 
ODP
Realm Mobile Database - An Introduction
Knoldus Inc.
 
PPTX
Java 7 Whats New(), Whats Next() from Oredev
Mattias Karlsson
 
PDF
Coding Ajax
Ted Husted
 
PPTX
Introduction to Client-Side Javascript
Julie Iskander
 
PDF
Building microservices with Kotlin
Haim Yadid
 
PDF
Painless Persistence with Realm
Christian Melchior
 
PPT
2011 Mongo FR - MongoDB introduction
antoinegirbal
 
PPT
Introduction to MongoDB
antoinegirbal
 
Real World Experience With Oracle Xml Database 11g An Oracle Ace’s Perspectiv...
Marco Gralike
 
NoSQL Endgame DevoxxUA Conference 2020
Thodoris Bais
 
NoSQL Endgame - Java2Days 2020 Virtual
Werner Keil
 
Http4s, Doobie and Circe: The Functional Web Stack
GaryCoady
 
Realm of the Mobile Database: an introduction to Realm
Martin Grider
 
Coding Ajax
Ted Husted
 
Realm Java 2.2.0: Build better apps, faster apps
Savvycom - Software Product Development
 
Realm Java 2.2.0: Build better apps, faster apps
Savvycom Savvycom
 
Kotlin for Android Development
Speck&Tech
 
Art of Javascript
Tarek Yehia
 
Boosting performance and functional style with Project Arrow from a practical...
João Esperancinha
 
Realm Mobile Database - An Introduction
Knoldus Inc.
 
Java 7 Whats New(), Whats Next() from Oredev
Mattias Karlsson
 
Coding Ajax
Ted Husted
 
Introduction to Client-Side Javascript
Julie Iskander
 
Building microservices with Kotlin
Haim Yadid
 
Painless Persistence with Realm
Christian Melchior
 
2011 Mongo FR - MongoDB introduction
antoinegirbal
 
Introduction to MongoDB
antoinegirbal
 
Ad

More from GlobalLogic Ukraine (20)

PDF
GlobalLogic JavaScript Community Webinar #21 “Інтерв’ю без заспокійливих”
GlobalLogic Ukraine
 
PPTX
Deadlocks in SQL - Turning Fear Into Understanding (by Sergii Stets)
GlobalLogic Ukraine
 
PDF
GlobalLogic Java Community Webinar #18 “How to Improve Web Application Perfor...
GlobalLogic Ukraine
 
PDF
GlobalLogic Embedded Community x ROS Ukraine Webinar "Surgical Robots"
GlobalLogic Ukraine
 
PDF
GlobalLogic Java Community Webinar #17 “SpringJDBC vs JDBC. Is Spring a Hero?”
GlobalLogic Ukraine
 
PDF
GlobalLogic JavaScript Community Webinar #18 “Long Story Short: OSI Model”
GlobalLogic Ukraine
 
PPTX
Штучний інтелект як допомога в навчанні, а не замінник.pptx
GlobalLogic Ukraine
 
PPTX
Задачі AI-розробника як застосовується штучний інтелект.pptx
GlobalLogic Ukraine
 
PPTX
Що треба вивчати, щоб стати розробником штучного інтелекту та нейромереж.pptx
GlobalLogic Ukraine
 
PDF
GlobalLogic Java Community Webinar #16 “Zaloni’s Architecture for Data-Driven...
GlobalLogic Ukraine
 
PDF
JavaScript Community Webinar #14 "Why Is Git Rebase?"
GlobalLogic Ukraine
 
PDF
GlobalLogic .NET Community Webinar #3 "Exploring Serverless with Azure Functi...
GlobalLogic Ukraine
 
PPTX
Страх і сила помилок - IT Inside від GlobalLogic Education
GlobalLogic Ukraine
 
PDF
GlobalLogic .NET Webinar #2 “Azure RBAC and Managed Identity”
GlobalLogic Ukraine
 
PDF
GlobalLogic QA Webinar “What does it take to become a Test Engineer”
GlobalLogic Ukraine
 
PDF
“How to Secure Your Applications With a Keycloak?
GlobalLogic Ukraine
 
PDF
GlobalLogic Machine Learning Webinar “Advanced Statistical Methods for Linear...
GlobalLogic Ukraine
 
PPTX
GlobalLogic Machine Learning Webinar “Statistical learning of linear regressi...
GlobalLogic Ukraine
 
PDF
GlobalLogic C++ Webinar “The Minimum Knowledge to Become a C++ Developer”
GlobalLogic Ukraine
 
PDF
Embedded Webinar #17 "Low-level Network Testing in Embedded Devices Development"
GlobalLogic Ukraine
 
GlobalLogic JavaScript Community Webinar #21 “Інтерв’ю без заспокійливих”
GlobalLogic Ukraine
 
Deadlocks in SQL - Turning Fear Into Understanding (by Sergii Stets)
GlobalLogic Ukraine
 
GlobalLogic Java Community Webinar #18 “How to Improve Web Application Perfor...
GlobalLogic Ukraine
 
GlobalLogic Embedded Community x ROS Ukraine Webinar "Surgical Robots"
GlobalLogic Ukraine
 
GlobalLogic Java Community Webinar #17 “SpringJDBC vs JDBC. Is Spring a Hero?”
GlobalLogic Ukraine
 
GlobalLogic JavaScript Community Webinar #18 “Long Story Short: OSI Model”
GlobalLogic Ukraine
 
Штучний інтелект як допомога в навчанні, а не замінник.pptx
GlobalLogic Ukraine
 
Задачі AI-розробника як застосовується штучний інтелект.pptx
GlobalLogic Ukraine
 
Що треба вивчати, щоб стати розробником штучного інтелекту та нейромереж.pptx
GlobalLogic Ukraine
 
GlobalLogic Java Community Webinar #16 “Zaloni’s Architecture for Data-Driven...
GlobalLogic Ukraine
 
JavaScript Community Webinar #14 "Why Is Git Rebase?"
GlobalLogic Ukraine
 
GlobalLogic .NET Community Webinar #3 "Exploring Serverless with Azure Functi...
GlobalLogic Ukraine
 
Страх і сила помилок - IT Inside від GlobalLogic Education
GlobalLogic Ukraine
 
GlobalLogic .NET Webinar #2 “Azure RBAC and Managed Identity”
GlobalLogic Ukraine
 
GlobalLogic QA Webinar “What does it take to become a Test Engineer”
GlobalLogic Ukraine
 
“How to Secure Your Applications With a Keycloak?
GlobalLogic Ukraine
 
GlobalLogic Machine Learning Webinar “Advanced Statistical Methods for Linear...
GlobalLogic Ukraine
 
GlobalLogic Machine Learning Webinar “Statistical learning of linear regressi...
GlobalLogic Ukraine
 
GlobalLogic C++ Webinar “The Minimum Knowledge to Become a C++ Developer”
GlobalLogic Ukraine
 
Embedded Webinar #17 "Low-level Network Testing in Embedded Devices Development"
GlobalLogic Ukraine
 

Recently uploaded (20)

PPTX
FUNDAMENTALS OF ELECTRIC VEHICLES UNIT-1
MikkiliSuresh
 
PDF
Introduction to Ship Engine Room Systems.pdf
Mahmoud Moghtaderi
 
PPTX
22PCOAM21 Session 1 Data Management.pptx
Guru Nanak Technical Institutions
 
PPT
1. SYSTEMS, ROLES, AND DEVELOPMENT METHODOLOGIES.ppt
zilow058
 
PPTX
MSME 4.0 Template idea hackathon pdf to understand
alaudeenaarish
 
PDF
Packaging Tips for Stainless Steel Tubes and Pipes
heavymetalsandtubes
 
PDF
STUDY OF NOVEL CHANNEL MATERIALS USING III-V COMPOUNDS WITH VARIOUS GATE DIEL...
ijoejnl
 
PDF
67243-Cooling and Heating & Calculation.pdf
DHAKA POLYTECHNIC
 
PDF
20ME702-Mechatronics-UNIT-1,UNIT-2,UNIT-3,UNIT-4,UNIT-5, 2025-2026
Mohanumar S
 
PDF
2025 Laurence Sigler - Advancing Decision Support. Content Management Ecommer...
Francisco Javier Mora Serrano
 
PDF
67243-Cooling and Heating & Calculation.pdf
DHAKA POLYTECHNIC
 
PPTX
Victory Precisions_Supplier Profile.pptx
victoryprecisions199
 
PPTX
22PCOAM21 Session 2 Understanding Data Source.pptx
Guru Nanak Technical Institutions
 
PPT
Understanding the Key Components and Parts of a Drone System.ppt
Siva Reddy
 
PPTX
Inventory management chapter in automation and robotics.
atisht0104
 
PPTX
IoT_Smart_Agriculture_Presentations.pptx
poojakumari696707
 
PDF
AI-Driven IoT-Enabled UAV Inspection Framework for Predictive Maintenance and...
ijcncjournal019
 
PDF
Unit I Part II.pdf : Security Fundamentals
Dr. Madhuri Jawale
 
PDF
Advanced LangChain & RAG: Building a Financial AI Assistant with Real-Time Data
Soufiane Sejjari
 
PDF
All chapters of Strength of materials.ppt
girmabiniyam1234
 
FUNDAMENTALS OF ELECTRIC VEHICLES UNIT-1
MikkiliSuresh
 
Introduction to Ship Engine Room Systems.pdf
Mahmoud Moghtaderi
 
22PCOAM21 Session 1 Data Management.pptx
Guru Nanak Technical Institutions
 
1. SYSTEMS, ROLES, AND DEVELOPMENT METHODOLOGIES.ppt
zilow058
 
MSME 4.0 Template idea hackathon pdf to understand
alaudeenaarish
 
Packaging Tips for Stainless Steel Tubes and Pipes
heavymetalsandtubes
 
STUDY OF NOVEL CHANNEL MATERIALS USING III-V COMPOUNDS WITH VARIOUS GATE DIEL...
ijoejnl
 
67243-Cooling and Heating & Calculation.pdf
DHAKA POLYTECHNIC
 
20ME702-Mechatronics-UNIT-1,UNIT-2,UNIT-3,UNIT-4,UNIT-5, 2025-2026
Mohanumar S
 
2025 Laurence Sigler - Advancing Decision Support. Content Management Ecommer...
Francisco Javier Mora Serrano
 
67243-Cooling and Heating & Calculation.pdf
DHAKA POLYTECHNIC
 
Victory Precisions_Supplier Profile.pptx
victoryprecisions199
 
22PCOAM21 Session 2 Understanding Data Source.pptx
Guru Nanak Technical Institutions
 
Understanding the Key Components and Parts of a Drone System.ppt
Siva Reddy
 
Inventory management chapter in automation and robotics.
atisht0104
 
IoT_Smart_Agriculture_Presentations.pptx
poojakumari696707
 
AI-Driven IoT-Enabled UAV Inspection Framework for Predictive Maintenance and...
ijcncjournal019
 
Unit I Part II.pdf : Security Fundamentals
Dr. Madhuri Jawale
 
Advanced LangChain & RAG: Building a Financial AI Assistant with Real-Time Data
Soufiane Sejjari
 
All chapters of Strength of materials.ppt
girmabiniyam1234
 

RealmDB for Android

  • 1. RealmDB. Fast & Simple by Anton Minashkin
  • 2. Whats wrong with SQLite + ORM? ● Boilerplate code ● SQL is ugly and hard to learn ● DTO <-> ORM ● Threads
  • 3. Realm is a mobile database Realm is a replacement for SQLite & Core Data. It can save you thousands of lines of code & weeks of work, and lets you craft amazing new user experiences.
  • 4. Realm is… blah-blah-blah… ...fast and simple data storage ...and cute ^_^
  • 5. History ● Comes from YCombinator ● TightDB -> Realm ● In development since 2011 ● 2nd-most deployed DB in the world (proof?)
  • 9. Why so fast? ● zero-copy architecture ● bitpacking reduces memory usage by up to 90% ● caching & vectorization makes access faster then native C ● built from scratch, based on C++ core ● proxy
  • 10. Models Field types: boolean, short, ìnt, long, float, double, String, Date and byte[] Annotations: @Ignore, @Index, @PrimaryKey
  • 11. Models public class User extends RealmObject { @PrimaryKey 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 dontPersist) { this.sessionId = sessionId; } }
  • 12. Writes ● Always use Transactions ● Writes block each other ● Use Realm.copyToRealm() ● Read & Writes are ACID
  • 13. Creating objects realm.beginTransaction(); User user = realm.createObject(User.class); user.setName("John"); user.setEmail("[email protected]"); realm.commitTransaction();
  • 14. Creating objects User user = new User("John"); user.setEmail("[email protected]"); realm.beginTransaction(); User realmUser = realm.copyToRealm(user); realm.commitTransaction();
  • 15. Transaction blocks realm.executeTransaction(new Realm.Transaction() { @Override public void execute(Realm realm) { User user = realm.createObject(User.class); user.setName("John"); user.setEmail("[email protected]"); } });
  • 16. Queries // Build the query looking at all users: RealmQuery<User> query = realm.where(User.class); // Add query conditions: query.equalTo("name", "John"); query.or().equalTo("name", "Peter"); // Execute the query: RealmResults<User> result1 = query.findAll();
  • 17. Queries RealmResults<User> result = realm.where(User.class) .equalTo("name", "John") .or() .equalTo("name", "Peter") .findAll();
  • 18. Retrieving objects by type Realm.allObjects(java.lang.Class<E> clazz) Realm.allObjectsSorted(...)
  • 19. Conditions ● between, greaterThan(), lessThan(), greaterThanOrEqualTo() & lessThanOrEqualTo() ● equalTo() & notEqualTo() ● contains(), beginsWith() & endsWith()
  • 20. Modifiers String conditions can ignore case for characters A-Z and a-z by using the CASE_INSENSITIVE modifier.
  • 21. Implicit Logical Operators RealmResults<User> r = realm.where(User.class) .greaterThan("age", 10) //AND .beginGroup() .equalTo("name", "Peter") .or() .contains("name", "Jo") .endGroup() .findAll();
  • 22. Sorting RealmResults<User> result = realm.where(User.class).findAll(); result.sort("age"); // Sort ascending result.sort("age", RealmResults.SORT_ORDER_DESCENDING);
  • 23. Chaining Queries RealmResults<User> teenagers = realm.where(User.class) .between("age", 13, 20).findAll(); RealmResults<User> firstJohn = teenagers.where().equalTo("name", "John").findFirst();
  • 24. Aggregation long sum = result.sum("age").longValue(); long min = result.min("age").longValue(); long max = result.max("age").longValue(); double average = result.average("age"); long matches = result.size();
  • 25. Iterations for (User u : result) { // ... do something with the object ... } for (int i = 0; i < result.size(); i++) { User u = result.get(i); // ... do something with the object ... }
  • 26. Deletion // All changes to data must happen in a transaction realm.beginTransaction(); // remove single match result.remove(0); result.removeLast(); // remove a single object Dog dog = result.get(5); dog.removeFromRealm(); // Delete all matches result.clear(); realm.commitTransaction()
  • 28. The Default Realm Realm.getInstance(Context context) Mapped to: default.realm Located in: Context.getFilesDir() --/data/data/files/ Check location: realm.getPath()
  • 29. Other Realms Realm realm = Realm.getInstance(this, "mycustom.realm");
  • 30. Using a Realm across Threads Realm, RealmObject or RealmResults instances cannot be passed across threads! Wanna same objects in other thread? Requery!
  • 31. Closing Realm instances Realm implements Closeable Realm instances are reference counted For the UI thread the easiest way is to execute realm.close() in the onDestroy() method.
  • 32. Auto-Refresh If a thread is associated with Looper (e.g. UI thread) then Realm has AutoRefresh feature; Check it: Realm.isAutoRefresh()
  • 33. Relationships public class Email extends RealmObject { private String address; private boolean active; // ... setters and getters left out } public class Contact extends RealmObject { private String name; private Email email; // ... setters and getters left out }
  • 34. Relationships public class Contact extends RealmObject { private RealmList<Email> emails; // Other fields… } RealmResults<Contact> contacts = realm .where(Contact.class) .equalTo("email.active", true).findAll();
  • 35. JSON Object should be represented as: String, JSONObject, InputStream // Insert from a string realm.beginTransaction(); realm.createObjectFromJson(City.class, "{ city: "Copenhagen", id: 1 }"); realm.commitTransaction();
  • 36. JSON // Insert multiple items using a InputStream InputStream is = new FileInputStream(new File("path_to_file")); realm.beginTransaction(); try { realm.createAllFromJson(City.class, is); realm.commitTransaction(); } catch (IOException e) { realm.cancelTransaction(); }
  • 37. Notifications realm.addChangeListener(new RealmChangeListener() { @Override public void onChange() { // ... do something with the updates (UI, etc.) ... } }); … realm.removeAllChangeListeners();
  • 38. Migrations Migrations are a work in progress. The feature is fully functional, but the current interface is cumbersome, and will be rewritten soon.
  • 39. Encryption Please take note of the Export Compliance section of our LICENSE, as it places restrictions against the usage of Realm if you are located in countries with an export restriction or embargo from the United States.
  • 40. Encryption byte[] key = new byte[32]; new SecureRandom().nextBytes(key); Realm realm = Realm.create(this, key); // ... use the Realm as normal ...
  • 41. Encryption Using Encryption requires building Realm from source: 1. Follow the normal build instructions, but before running ./gradlew assemble, add the lineencryption=true to local.properties. 2. After building Realm, replace the copy of realm-<VERSION>.aar in your project with the one found at realm/build/outputs/aar/realm- <VERSION>.aar.
  • 42. Adapter public class MyAdapter extends RealmBaseAdapter<TimeStamp> implements ListAdapter { … @Override public View getView(int position, View convertView, ViewGroup parent) {...} }
  • 44. Realm Browser Only available on Mac OS X at the moment! We are working on Windows & Linux versions.
  • 46. Current limitations (still beta) General: 1. The upper limit of class names is 57 characters. Realm for Android prepend class_ to all names, and the browser will show it as part of the name. 2. The length of field names has a upper limit of 63 character. 3. The dates are truncated with a precision of one second. In order to maintain compability between 32 bits and 64 bits devices, it is not possible to store dates before 1900-12-13 and after 2038-01-19.
  • 47. Current limitations (still beta) General: 4. Nested transactions are not supported, and an exception is throw if it is detected. 5. Strings and byte arrays (byte[]) cannot be larger than 16 MB. 6. Case insensitive string matches in queries are only supported for character sets in ‘Latin Basic’, ‘Latin Supplement’, ‘Latin Extended A’, ‘Latin Extended B’ (UTF-8 range 0-591).
  • 48. Current limitations (still beta) Sorting Sorting is currently limited to character sets in ‘Latin Basic’, ‘Latin Supplement’, ‘Latin Extended A’, ‘Latin Extended B’ (UTF-8 range 0-591). For other charsets, sorting will not change the RealmResults object.
  • 49. Current limitations (still beta) Threads Although Realm files can be accessed by multiple threads concurrently, you cannot hand over Realms, Realm objects, queries, and results between threads. Moreover, asynchronous queries are currently not supported.
  • 50. Current limitations (still beta) null values It is not possible to store null as a value for primitive data types (booleans, integers, floating-point numbers, dates, and strings). Supporting null is under active development but until fully supported, we suggest that you add an extra boolean field to capture if a field is null or not.
  • 51. Current limitations (still beta) Realm files cannot be accessed by concurrent processes Although Realm files can be accessed by multiple threads concurrently, they can only be accessed by a single process at a time. Different processes should either copy Realm files or create their own. Multi-process support is coming soon.