SlideShare a Scribd company logo
1 of 53
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

What's hot

20100712-OTcl Command -- Getting Started
20100712-OTcl Command -- Getting Started20100712-OTcl Command -- Getting Started
20100712-OTcl Command -- Getting Started
Teerawat Issariyakul
 
AST Transformations at JFokus
AST Transformations at JFokusAST Transformations at JFokus
AST Transformations at JFokus
HamletDRC
 
ooc - OSDC 2010 - Amos Wenger
ooc - OSDC 2010 - Amos Wengerooc - OSDC 2010 - Amos Wenger
ooc - OSDC 2010 - Amos Wenger
Amos Wenger
 

What's hot (20)

20100712-OTcl Command -- Getting Started
20100712-OTcl Command -- Getting Started20100712-OTcl Command -- Getting Started
20100712-OTcl Command -- Getting Started
 
Full Stack Clojure
Full Stack ClojureFull Stack Clojure
Full Stack Clojure
 
The Ring programming language version 1.10 book - Part 22 of 212
The Ring programming language version 1.10 book - Part 22 of 212The Ring programming language version 1.10 book - Part 22 of 212
The Ring programming language version 1.10 book - Part 22 of 212
 
Out ofmemoryerror what is the cost of java objects
Out ofmemoryerror  what is the cost of java objectsOut ofmemoryerror  what is the cost of java objects
Out ofmemoryerror what is the cost of java objects
 
NS2 Object Construction
NS2 Object ConstructionNS2 Object Construction
NS2 Object Construction
 
AST Transformations at JFokus
AST Transformations at JFokusAST Transformations at JFokus
AST Transformations at JFokus
 
Java Concurrency Idioms
Java Concurrency IdiomsJava Concurrency Idioms
Java Concurrency Idioms
 
DConf 2016: Keynote by Walter Bright
DConf 2016: Keynote by Walter Bright DConf 2016: Keynote by Walter Bright
DConf 2016: Keynote by Walter Bright
 
Codable routing
Codable routingCodable routing
Codable routing
 
ClojureScript for the web
ClojureScript for the webClojureScript for the web
ClojureScript for the web
 
Hw09 Hadoop + Clojure
Hw09   Hadoop + ClojureHw09   Hadoop + Clojure
Hw09 Hadoop + Clojure
 
Kotlin – the future of android
Kotlin – the future of androidKotlin – the future of android
Kotlin – the future of android
 
Dynamic C++ ACCU 2013
Dynamic C++ ACCU 2013Dynamic C++ ACCU 2013
Dynamic C++ ACCU 2013
 
Meetup slides
Meetup slidesMeetup slides
Meetup slides
 
ClojureScript loves React, DomCode May 26 2015
ClojureScript loves React, DomCode May 26 2015ClojureScript loves React, DomCode May 26 2015
ClojureScript loves React, DomCode May 26 2015
 
New Indexing and Aggregation Pipeline Capabilities in MongoDB 4.2
New Indexing and Aggregation Pipeline Capabilities in MongoDB 4.2New Indexing and Aggregation Pipeline Capabilities in MongoDB 4.2
New Indexing and Aggregation Pipeline Capabilities in MongoDB 4.2
 
Scala
ScalaScala
Scala
 
ooc - OSDC 2010 - Amos Wenger
ooc - OSDC 2010 - Amos Wengerooc - OSDC 2010 - Amos Wenger
ooc - OSDC 2010 - Amos Wenger
 
Java Concurrency Gotchas
Java Concurrency GotchasJava Concurrency Gotchas
Java Concurrency Gotchas
 
Hadoop + Clojure
Hadoop + ClojureHadoop + Clojure
Hadoop + Clojure
 

Similar to RealmDB for Android

Similar to RealmDB for Android (20)

Real World Experience With Oracle Xml Database 11g An Oracle Ace’s Perspectiv...
Real World Experience With Oracle Xml Database 11g An Oracle Ace’s Perspectiv...Real World Experience With Oracle Xml Database 11g An Oracle Ace’s Perspectiv...
Real World Experience With Oracle Xml Database 11g An Oracle Ace’s Perspectiv...
 
NoSQL Endgame DevoxxUA Conference 2020
NoSQL Endgame DevoxxUA Conference 2020NoSQL Endgame DevoxxUA Conference 2020
NoSQL Endgame DevoxxUA Conference 2020
 
NoSQL Endgame - Java2Days 2020 Virtual
NoSQL Endgame - Java2Days 2020 VirtualNoSQL Endgame - Java2Days 2020 Virtual
NoSQL Endgame - Java2Days 2020 Virtual
 
Http4s, Doobie and Circe: The Functional Web Stack
Http4s, Doobie and Circe: The Functional Web StackHttp4s, Doobie and Circe: The Functional Web Stack
Http4s, Doobie and Circe: The Functional Web Stack
 
Realm of the Mobile Database: an introduction to Realm
Realm of the Mobile Database: an introduction to RealmRealm of the Mobile Database: an introduction to Realm
Realm of the Mobile Database: an introduction to Realm
 
Coding Ajax
Coding AjaxCoding Ajax
Coding Ajax
 
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
 
Java
JavaJava
Java
 
Kotlin for Android Development
Kotlin for Android DevelopmentKotlin for Android Development
Kotlin for Android Development
 
Art of Javascript
Art of JavascriptArt of Javascript
Art of Javascript
 
Realm Mobile Database - An Introduction
Realm Mobile Database - An IntroductionRealm Mobile Database - An Introduction
Realm Mobile Database - An Introduction
 
Java 7 Whats New(), Whats Next() from Oredev
Java 7 Whats New(), Whats Next() from OredevJava 7 Whats New(), Whats Next() from Oredev
Java 7 Whats New(), Whats Next() from Oredev
 
Coding Ajax
Coding AjaxCoding Ajax
Coding Ajax
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side Javascript
 
Building microservices with Kotlin
Building microservices with KotlinBuilding microservices with Kotlin
Building microservices with Kotlin
 
Painless Persistence with Realm
Painless Persistence with RealmPainless Persistence with Realm
Painless Persistence with Realm
 
Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDB
 
2011 Mongo FR - MongoDB introduction
2011 Mongo FR - MongoDB introduction2011 Mongo FR - MongoDB introduction
2011 Mongo FR - MongoDB introduction
 
NET Systems Programming Learned the Hard Way.pptx
NET Systems Programming Learned the Hard Way.pptxNET Systems Programming Learned the Hard Way.pptx
NET Systems Programming Learned the Hard Way.pptx
 

More from GlobalLogic Ukraine

GlobalLogic Machine Learning Webinar “Advanced Statistical Methods for Linear...
GlobalLogic Machine Learning Webinar “Advanced Statistical Methods for Linear...GlobalLogic Machine Learning Webinar “Advanced Statistical Methods for Linear...
GlobalLogic Machine Learning Webinar “Advanced Statistical Methods for Linear...
GlobalLogic Ukraine
 

More from GlobalLogic Ukraine (20)

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

Recently uploaded

Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
ssuser89054b
 
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night StandCall Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
amitlee9823
 
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
dollysharma2066
 

Recently uploaded (20)

data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdf
 
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELLPVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
 
NFPA 5000 2024 standard .
NFPA 5000 2024 standard                                  .NFPA 5000 2024 standard                                  .
NFPA 5000 2024 standard .
 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPT
 
Double Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueDouble Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torque
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performance
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
 
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...
 
Thermal Engineering Unit - I & II . ppt
Thermal Engineering  Unit - I & II . pptThermal Engineering  Unit - I & II . ppt
Thermal Engineering Unit - I & II . ppt
 
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
 
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
 
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
 
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night StandCall Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
 
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordCCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
 
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdf
 
Double rodded leveling 1 pdf activity 01
Double rodded leveling 1 pdf activity 01Double rodded leveling 1 pdf activity 01
Double rodded leveling 1 pdf activity 01
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.ppt
 

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("john@corporation.com"); realm.commitTransaction();
  • 14. Creating objects User user = new User("John"); user.setEmail("john@corporation.com"); 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("john@corporation.com"); } });
  • 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.