SlideShare a Scribd company logo
1 of 50
Realm
HowILearnedto
StopWorrying
andLovemyApp
Database
or
Sergi Martínez
Android Developer at Schibsted Spain
Android GDE
@sergiandreplace
The usual stuff
My big server
My big database
My mobile app
My little
database
My
nice
API
The internet!
The usual stuff
My big server
My big database
My mobile app
My little
database
My
nice
API
The internet!
This tries to mimic this
The usual stuff
My big server
My big database
My mobile app
My little
database
My
nice
API
The internet!
Here We only need
to cache entities
The initial solution
SQLite
SQLite
SQL language
Relationships
Non-java data types
SQL Queries
SQL stuff
SQLite
SQL language
Relationships
Non-java data types
SQL Queries
SQL stuff
Do we need these?
SQLite
SQL language
Relationships
Non-java data types
SQL Queries
SQL stuff
Do we need these?
Really?
Also...
SQLDbHelper
SQL Queries
Content Providers
Loaders
etc
Also...
SQLDbHelper
SQL Queries
Content Providers
Loaders
etc
Boilerplate
Also...
SQLDbHelper
SQL Queries
Content Providers
Loaders
etc
Boilerplate
Boilerplate
Also...
SQLDbHelper
SQL Queries
Content Providers
Loaders
etc
Boilerplate
Boilerplate
OH! Wow! So much boilerplate
Also...
SQLDbHelper
SQL Queries
Content Providers
Loaders
etc
Boilerplate
Boilerplate
OH! Wow! So much boilerplate
“Hard” to create. Excessive coupling with
UI
Also...
SQLDbHelper
SQL Queries
Content Providers
Loaders
etc
Boilerplate
Boilerplate
OH! Wow! So much boilerplate
“Hard” to create. Excessive coupling with
UI
Probably… more boilerplate
Let’s try something different… Realm
It stores objects
Hierarchical relationships (sort of)
No boilerplate (just probably mappers)
Fast!
Reduces dev time drastically
Adding Realm to your project
Your project build.gradle
buildscript {
repositories {
jcenter()
}
dependencies {
classpath "io.realm:realm-gradle-plugin:0.89.0"
}
}
apply plugin: 'realm-android'
Your app build.gradle
Realm Objects
public class Minion extends RealmObject {
private String name;
private int eyes;
private boolean goggles;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public int getEyes() { return eyes; }
public void setEyes(int eyes) { this.eyes = eyes; }
public boolean hasGoggles() { return goggles; }
public void setGoggles(boolean goggles) { this.goggles = goggles; }
}
Realm Objects
public class Minion extends RealmObject {
private String name;
private int eyes;
private boolean goggles;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public int getEyes() { return eyes; }
public void setEyes(int eyes) { this.eyes = eyes; }
public boolean hasGoggles() { return goggles; }
public void setGoggles(boolean goggles) { this.goggles = goggles; }
}
Must extend RealmObject
Realm Objects
public class Minion extends RealmObject {
private String name;
private int eyes;
private boolean goggles;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public int getEyes() { return eyes; }
public void setEyes(int eyes) { this.eyes = eyes; }
public boolean hasGoggles() { return goggles; }
public void setGoggles(boolean goggles) { this.goggles = goggles; }
}
Must extend RealmObject
Not exactly true since last thursday (#$%@!). More later...
Realm Objects
public class Minion extends RealmObject {
private String name;
private int eyes;
private boolean goggles;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public int getEyes() { return eyes; }
public void setEyes(int eyes) { this.eyes = eyes; }
public boolean hasGoggles() { return goggles; }
public void setGoggles(boolean goggles) { this.goggles = goggles; }
}
Object members that will be stored
More on types later
Realm Objects
public class Minion extends RealmObject {
private String name;
private int eyes;
private boolean goggles;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public int getEyes() { return eyes; }
public void setEyes(int eyes) { this.eyes = eyes; }
public boolean hasGoggles() { return goggles; }
public void setGoggles(boolean goggles) { this.goggles = goggles; }
}
Usual getters and setters
Supported data types
boolean/Boolean
byte/Byte
short/Short
int/Integer
long/Long
float/Float
double/Double
String
Date
Byte[]
Storing an object
realm.beginTransaction();
Minion minion = realm.createObject(Minion.class);
minion.setName("Bob");
minion.setEyes(1);
minion.setGoggles(true);
realm.commitTransaction();
realm.cancelTransaction();
or
First, we start a transaction
Storing an object
realm.beginTransaction();
Minion minion = realm.createObject(Minion.class);
minion.setName("Bob");
minion.setEyes(1);
minion.setGoggles(true);
realm.commitTransaction();
realm.cancelTransaction();
or
Then we create an instance inside our realm
Storing an object
realm.beginTransaction();
Minion minion = realm.createObject(Minion.class);
minion.setName("Bob");
minion.setEyes(1);
minion.setGoggles(true);
realm.commitTransaction();
realm.cancelTransaction();
or
We set the values
Storing an object
realm.beginTransaction();
Minion minion = realm.createObject(Minion.class);
minion.setName("Bob");
minion.setEyes(1);
minion.setGoggles(true);
realm.commitTransaction();
realm.cancelTransaction();
or
And commit the transaction. Then, our changes are saved
Storing an object
realm.beginTransaction();
Minion minion = realm.createObject(Minion.class);
minion.setName("Bob");
minion.setEyes(1);
minion.setGoggles(true);
realm.commitTransaction();
realm.cancelTransaction();
or
Or we cancel the transaction and the new object is discarded
Storing an object - II
Minion minion = new Minion();
minion.setName("Bob");
minion.setEyes(1);
minion.setGoggles(true);
realm.beginTransaction();
realm.copyToRealm(minion);
realm.commitTransaction();
Another way. We create the object outside the realm
Storing an object - II
Minion minion = new Minion();
minion.setName("Bob");
minion.setEyes(1);
minion.setGoggles(true);
realm.beginTransaction();
realm.copyToRealm(minion);
realm.commitTransaction();
Then, we begin a transaction, copy the object into the realm, and commit
Obtaining your Realm
First, create your Realm configuration
RealmConfiguration config = new RealmConfiguration.Builder(context)
.name("myrealm.realm")
.encryptionKey(getKey())
.schemaVersion(42)
.setModules(new MySchemaModule())
.migration(new MyMigration())
.build();
Obtaining your Realm
Then, get an instance
RealmConfiguration config = new RealmConfiguration.Builder(context)
.name("myrealm.realm")
.encryptionKey(getKey())
.schemaVersion(42)
.setModules(new MySchemaModule())
.migration(new MyMigration())
.build();
Realm myRealm = Realm.getInstance(config);
Obtaining your Realm
Or use the default Realm Instance
RealmConfiguration config = new RealmConfiguration.Builder(context)
.name("myrealm.realm")
.encryptionKey(getKey())
.schemaVersion(42)
.setModules(new MySchemaModule())
.migration(new MyMigration())
.build();
Realm.setDefaultConfiguration(config);
And obtain it anywhere
Realm realm = Realm.getDefaultInstance();
// Stuff
realm.close();
Close your Realms
For each
Realm.getDefaultInstance()
or
Realm.getInstance()
you must execute realm.close() at the end
Querying a Realm
Realm uses fluent syntax. Just create a RealmQuery object based on the Realm class you want
RealmQuery<Minion> query = realm.where(Minion.class);
Add operations and filters and execute
RealmResults<Minion> results = query.equalTo(“name”, “Bob”).findAll();
Do something with the result
for (Minion minion:results) {
…. //Do stuff
}
Query operators
between()
greaterThan()
lessThan()
greaterThanOrEqual()
lessThanOrEqual()
equalTo()
notEqualTo()
contains()
beginsWith()
endsWith()
Annotations
@Index
@PrimaryKey
@Ignore
@Required
Relationships - 1:N
Just have a RealmObject with a RealmObject
public class Minion extends RealmObject {
private String name;
private int eyes;
private boolean goggles;
private Banana banana
//Getters, setters and so on
}
Public class Banana extends RealmObject {
…
}
Storing 1:N related objects
realm.beginTransaction()
Banana banana = realm.createObject(Banana.class);
banana.setSomething…
Minion minion = realm.createObject(Minion.class);
minion.setName(“Bob”);
minion.setBanana(banana);
realm.writeTransaction();
Relationships - M:N
Just have a RealmObject with a List<? extends RealmObject>
public class Minion extends RealmObject {
private String name;
private int eyes;
private boolean goggles;
private RealmList<Banana> bananas
//Getters, setters and so on
}
Public class Banana extends RealmObject {
…
}
Storing M:N related objects
realm.beginTransaction()
Banana banana = realm.createObject(Banana.class);
banana.setSomething…
Minion minion = realm.createObject(Minion.class);
minion.setName(“Bob”);
minion.getBananas().add(banana);
realm.writeTransaction();
Querying M:N related objects
RealmResults<Minion> minions = realm.where(Minions.class)
.equalTo("banana.size", "big")
.findAll();
Threading
Each Realm should live in the same Thread is has been created
You can’t pass Realms between threads
Realms are automatically updated between threads IF they are in threads with a Looper
Otherwise… Realm.refresh()
More things
Dynamic realms
Schemas
Migrations
UI controls
Browsers
etc...
Brand new changes
This week on Realm:
RealmModel interface + static methods
RealmCollection/RealmOrderedCollection Interfaces
Primary keys can be null!
How I use it
public abstract class VOBaseMapper<V extends RealmObject,E> {
public abstract V toVO(E entity);
public abstract E toEntity(V vo) ;
public RealmList<V> toVO(List<E> entities) {
RealmList<V> realmList=new RealmList<V>();
for (E entity:entities) {
realmList.add(toVO(entity));
}
return realmList;
}
How I use it
public List<E> toEntity(RealmList<V> vos) {
List<E> applicationEntityList = new ArrayList<>();
for(V vo :vos){
applicationEntityList.add(toEntity(vo));
}
return applicationEntityList;
}
public List<E> toEntity(RealmResults<V> vos) {
List<E> applicationEntityList = new ArrayList<>();
for(V vo :vos){
applicationEntityList.add(toEntity(vo));
}
return applicationEntityList;
}
}
How I use it
public class UserVOMapper extends VOBaseMapper<UserVO,User > {
private User user;
@Override
public UserVO toVO(User user) {
UserVO vo=new UserVO();
vo.setName(user.name);
vo.setEmail(user.email);
return vo;
}
@Override
public User toEntity(UserVO vo) {
User user= new User();
user.name=vo.getName();
user.email=vo.getEmail();
return user;
}
}
And that’s not all
But enough for today.
Questions?
@sergiandreplace
Thanks for coming

More Related Content

What's hot

Getting started with Elasticsearch and .NET
Getting started with Elasticsearch and .NETGetting started with Elasticsearch and .NET
Getting started with Elasticsearch and .NETTomas Jansson
 
JSON and Swift, Still A Better Love Story Than Twilight
JSON and Swift, Still A Better Love Story Than TwilightJSON and Swift, Still A Better Love Story Than Twilight
JSON and Swift, Still A Better Love Story Than TwilightDonny Wals
 
GreenDao Introduction
GreenDao IntroductionGreenDao Introduction
GreenDao IntroductionBooch Lin
 
Morphia: Simplifying Persistence for Java and MongoDB
Morphia:  Simplifying Persistence for Java and MongoDBMorphia:  Simplifying Persistence for Java and MongoDB
Morphia: Simplifying Persistence for Java and MongoDBJeff Yemin
 
Groovy and Grails in Action - Devoxx 2008 - University - Guillaume Laforge
Groovy and Grails in Action - Devoxx 2008 - University - Guillaume LaforgeGroovy and Grails in Action - Devoxx 2008 - University - Guillaume Laforge
Groovy and Grails in Action - Devoxx 2008 - University - Guillaume LaforgeGuillaume Laforge
 
Beginning icloud development - Cesare Rocchi - WhyMCA
Beginning icloud development - Cesare Rocchi - WhyMCABeginning icloud development - Cesare Rocchi - WhyMCA
Beginning icloud development - Cesare Rocchi - WhyMCAWhymca
 
The Testing Games: Mocking, yay!
The Testing Games: Mocking, yay!The Testing Games: Mocking, yay!
The Testing Games: Mocking, yay!Donny Wals
 
Data access 2.0? Please welcome: Spring Data!
Data access 2.0? Please welcome: Spring Data!Data access 2.0? Please welcome: Spring Data!
Data access 2.0? Please welcome: Spring Data!Oliver Gierke
 
Webinar: MongoDB Persistence with Java and Morphia
Webinar: MongoDB Persistence with Java and MorphiaWebinar: MongoDB Persistence with Java and Morphia
Webinar: MongoDB Persistence with Java and MorphiaMongoDB
 
Simplifying Persistence for Java and MongoDB with Morphia
Simplifying Persistence for Java and MongoDB with MorphiaSimplifying Persistence for Java and MongoDB with Morphia
Simplifying Persistence for Java and MongoDB with MorphiaMongoDB
 
Lowering in C#: What really happens with your code?, from NDC Oslo 2019
Lowering in C#: What really happens with your code?, from NDC Oslo 2019Lowering in C#: What really happens with your code?, from NDC Oslo 2019
Lowering in C#: What really happens with your code?, from NDC Oslo 2019David Wengier
 
Art of Javascript
Art of JavascriptArt of Javascript
Art of JavascriptTarek Yehia
 
TDC2016SP - Trilha .NET
TDC2016SP - Trilha .NETTDC2016SP - Trilha .NET
TDC2016SP - Trilha .NETtdc-globalcode
 
Ten useful JavaScript tips & best practices
Ten useful JavaScript tips & best practicesTen useful JavaScript tips & best practices
Ten useful JavaScript tips & best practicesAnkit Rastogi
 
Developing application for Windows Phone 7 in TDD
Developing application for Windows Phone 7 in TDDDeveloping application for Windows Phone 7 in TDD
Developing application for Windows Phone 7 in TDDMichele Capra
 
Kotlin Data Model
Kotlin Data ModelKotlin Data Model
Kotlin Data ModelKros Huang
 
Solid Software Design Principles
Solid Software Design PrinciplesSolid Software Design Principles
Solid Software Design PrinciplesJon Kruger
 

What's hot (20)

Green dao
Green daoGreen dao
Green dao
 
Getting started with Elasticsearch and .NET
Getting started with Elasticsearch and .NETGetting started with Elasticsearch and .NET
Getting started with Elasticsearch and .NET
 
JSON and Swift, Still A Better Love Story Than Twilight
JSON and Swift, Still A Better Love Story Than TwilightJSON and Swift, Still A Better Love Story Than Twilight
JSON and Swift, Still A Better Love Story Than Twilight
 
Whats new in iOS5
Whats new in iOS5Whats new in iOS5
Whats new in iOS5
 
GreenDao Introduction
GreenDao IntroductionGreenDao Introduction
GreenDao Introduction
 
Green dao
Green daoGreen dao
Green dao
 
Morphia: Simplifying Persistence for Java and MongoDB
Morphia:  Simplifying Persistence for Java and MongoDBMorphia:  Simplifying Persistence for Java and MongoDB
Morphia: Simplifying Persistence for Java and MongoDB
 
Groovy and Grails in Action - Devoxx 2008 - University - Guillaume Laforge
Groovy and Grails in Action - Devoxx 2008 - University - Guillaume LaforgeGroovy and Grails in Action - Devoxx 2008 - University - Guillaume Laforge
Groovy and Grails in Action - Devoxx 2008 - University - Guillaume Laforge
 
Beginning icloud development - Cesare Rocchi - WhyMCA
Beginning icloud development - Cesare Rocchi - WhyMCABeginning icloud development - Cesare Rocchi - WhyMCA
Beginning icloud development - Cesare Rocchi - WhyMCA
 
The Testing Games: Mocking, yay!
The Testing Games: Mocking, yay!The Testing Games: Mocking, yay!
The Testing Games: Mocking, yay!
 
Data access 2.0? Please welcome: Spring Data!
Data access 2.0? Please welcome: Spring Data!Data access 2.0? Please welcome: Spring Data!
Data access 2.0? Please welcome: Spring Data!
 
Webinar: MongoDB Persistence with Java and Morphia
Webinar: MongoDB Persistence with Java and MorphiaWebinar: MongoDB Persistence with Java and Morphia
Webinar: MongoDB Persistence with Java and Morphia
 
Simplifying Persistence for Java and MongoDB with Morphia
Simplifying Persistence for Java and MongoDB with MorphiaSimplifying Persistence for Java and MongoDB with Morphia
Simplifying Persistence for Java and MongoDB with Morphia
 
Lowering in C#: What really happens with your code?, from NDC Oslo 2019
Lowering in C#: What really happens with your code?, from NDC Oslo 2019Lowering in C#: What really happens with your code?, from NDC Oslo 2019
Lowering in C#: What really happens with your code?, from NDC Oslo 2019
 
Art of Javascript
Art of JavascriptArt of Javascript
Art of Javascript
 
TDC2016SP - Trilha .NET
TDC2016SP - Trilha .NETTDC2016SP - Trilha .NET
TDC2016SP - Trilha .NET
 
Ten useful JavaScript tips & best practices
Ten useful JavaScript tips & best practicesTen useful JavaScript tips & best practices
Ten useful JavaScript tips & best practices
 
Developing application for Windows Phone 7 in TDD
Developing application for Windows Phone 7 in TDDDeveloping application for Windows Phone 7 in TDD
Developing application for Windows Phone 7 in TDD
 
Kotlin Data Model
Kotlin Data ModelKotlin Data Model
Kotlin Data Model
 
Solid Software Design Principles
Solid Software Design PrinciplesSolid Software Design Principles
Solid Software Design Principles
 

Viewers also liked

My way to clean android (EN) - Android day salamanca edition
My way to clean android (EN) - Android day salamanca editionMy way to clean android (EN) - Android day salamanca edition
My way to clean android (EN) - Android day salamanca editionChristian Panadero
 
It's the arts! Playing around with the Android canvas
It's the arts! Playing around with the Android canvasIt's the arts! Playing around with the Android canvas
It's the arts! Playing around with the Android canvasSergi Martínez
 
[Android] 2D Graphics
[Android] 2D Graphics[Android] 2D Graphics
[Android] 2D GraphicsNikmesoft Ltd
 
Introduction to Android Fragments
Introduction to Android FragmentsIntroduction to Android Fragments
Introduction to Android FragmentsSergi Martínez
 

Viewers also liked (8)

Admob y yo
Admob y yoAdmob y yo
Admob y yo
 
Android master class
Android master classAndroid master class
Android master class
 
Introducción a mobclix
Introducción a mobclixIntroducción a mobclix
Introducción a mobclix
 
My way to clean android (EN) - Android day salamanca edition
My way to clean android (EN) - Android day salamanca editionMy way to clean android (EN) - Android day salamanca edition
My way to clean android (EN) - Android day salamanca edition
 
It's the arts! Playing around with the Android canvas
It's the arts! Playing around with the Android canvasIt's the arts! Playing around with the Android canvas
It's the arts! Playing around with the Android canvas
 
[Android] 2D Graphics
[Android] 2D Graphics[Android] 2D Graphics
[Android] 2D Graphics
 
Android data binding
Android data bindingAndroid data binding
Android data binding
 
Introduction to Android Fragments
Introduction to Android FragmentsIntroduction to Android Fragments
Introduction to Android Fragments
 

Similar to Realm or: How I learned to stop worrying and love my app database

Launching Beeline with Firebase
Launching Beeline with FirebaseLaunching Beeline with Firebase
Launching Beeline with FirebaseChetan Padia
 
Introduction to Spring Boot.pdf
Introduction to Spring Boot.pdfIntroduction to Spring Boot.pdf
Introduction to Spring Boot.pdfShaiAlmog1
 
JavaScript Functions
JavaScript FunctionsJavaScript Functions
JavaScript FunctionsColin DeCarlo
 
BDD, ATDD, Page Objects: The Road to Sustainable Web Testing
BDD, ATDD, Page Objects: The Road to Sustainable Web TestingBDD, ATDD, Page Objects: The Road to Sustainable Web Testing
BDD, ATDD, Page Objects: The Road to Sustainable Web TestingJohn Ferguson Smart Limited
 
Painless Persistence in a Disconnected World
Painless Persistence in a Disconnected WorldPainless Persistence in a Disconnected World
Painless Persistence in a Disconnected WorldChristian Melchior
 
Diving in the Flex Data Binding Waters
Diving in the Flex Data Binding WatersDiving in the Flex Data Binding Waters
Diving in the Flex Data Binding Watersmichael.labriola
 
Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...go_oh
 
Construire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradleConstruire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradleThierry Wasylczenko
 
Be More Productive with Kotlin
Be More Productive with KotlinBe More Productive with Kotlin
Be More Productive with KotlinBrandon Wever
 
properties-how-do-i - Transcript.pdf
properties-how-do-i - Transcript.pdfproperties-how-do-i - Transcript.pdf
properties-how-do-i - Transcript.pdfShaiAlmog1
 
The uniform interface is 42
The uniform interface is 42The uniform interface is 42
The uniform interface is 42Yevhen Bobrov
 
Kotlin/Everywhere GDG Bhubaneswar 2019
Kotlin/Everywhere GDG Bhubaneswar 2019 Kotlin/Everywhere GDG Bhubaneswar 2019
Kotlin/Everywhere GDG Bhubaneswar 2019 Sriyank Siddhartha
 
Having Fun with Kotlin Android - DILo Surabaya
Having Fun with Kotlin Android - DILo SurabayaHaving Fun with Kotlin Android - DILo Surabaya
Having Fun with Kotlin Android - DILo SurabayaDILo Surabaya
 
A GWT Application with MVP Pattern Deploying to CloudFoundry using Spring Roo
A GWT Application with MVP Pattern Deploying to CloudFoundry using  Spring Roo A GWT Application with MVP Pattern Deploying to CloudFoundry using  Spring Roo
A GWT Application with MVP Pattern Deploying to CloudFoundry using Spring Roo Ali Parmaksiz
 
Advanced realm in swift
Advanced realm in swiftAdvanced realm in swift
Advanced realm in swiftYusuke Kita
 
Ian 20150116 java script oop
Ian 20150116 java script oopIan 20150116 java script oop
Ian 20150116 java script oopLearningTech
 

Similar to Realm or: How I learned to stop worrying and love my app database (20)

Android workshop
Android workshopAndroid workshop
Android workshop
 
Launching Beeline with Firebase
Launching Beeline with FirebaseLaunching Beeline with Firebase
Launching Beeline with Firebase
 
Introduction to Spring Boot.pdf
Introduction to Spring Boot.pdfIntroduction to Spring Boot.pdf
Introduction to Spring Boot.pdf
 
Kotlin Generation
Kotlin GenerationKotlin Generation
Kotlin Generation
 
JavaScript Functions
JavaScript FunctionsJavaScript Functions
JavaScript Functions
 
SOLID Principles
SOLID PrinciplesSOLID Principles
SOLID Principles
 
BDD, ATDD, Page Objects: The Road to Sustainable Web Testing
BDD, ATDD, Page Objects: The Road to Sustainable Web TestingBDD, ATDD, Page Objects: The Road to Sustainable Web Testing
BDD, ATDD, Page Objects: The Road to Sustainable Web Testing
 
Painless Persistence in a Disconnected World
Painless Persistence in a Disconnected WorldPainless Persistence in a Disconnected World
Painless Persistence in a Disconnected World
 
Diving in the Flex Data Binding Waters
Diving in the Flex Data Binding WatersDiving in the Flex Data Binding Waters
Diving in the Flex Data Binding Waters
 
Dependency Injection
Dependency InjectionDependency Injection
Dependency Injection
 
Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...
 
Construire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradleConstruire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradle
 
Be More Productive with Kotlin
Be More Productive with KotlinBe More Productive with Kotlin
Be More Productive with Kotlin
 
properties-how-do-i - Transcript.pdf
properties-how-do-i - Transcript.pdfproperties-how-do-i - Transcript.pdf
properties-how-do-i - Transcript.pdf
 
The uniform interface is 42
The uniform interface is 42The uniform interface is 42
The uniform interface is 42
 
Kotlin/Everywhere GDG Bhubaneswar 2019
Kotlin/Everywhere GDG Bhubaneswar 2019 Kotlin/Everywhere GDG Bhubaneswar 2019
Kotlin/Everywhere GDG Bhubaneswar 2019
 
Having Fun with Kotlin Android - DILo Surabaya
Having Fun with Kotlin Android - DILo SurabayaHaving Fun with Kotlin Android - DILo Surabaya
Having Fun with Kotlin Android - DILo Surabaya
 
A GWT Application with MVP Pattern Deploying to CloudFoundry using Spring Roo
A GWT Application with MVP Pattern Deploying to CloudFoundry using  Spring Roo A GWT Application with MVP Pattern Deploying to CloudFoundry using  Spring Roo
A GWT Application with MVP Pattern Deploying to CloudFoundry using Spring Roo
 
Advanced realm in swift
Advanced realm in swiftAdvanced realm in swift
Advanced realm in swift
 
Ian 20150116 java script oop
Ian 20150116 java script oopIan 20150116 java script oop
Ian 20150116 java script oop
 

More from Sergi Martínez

Kotlin, a modern language for modern times
Kotlin, a modern language for modern timesKotlin, a modern language for modern times
Kotlin, a modern language for modern timesSergi Martínez
 
What is flutter and why should i care?
What is flutter and why should i care?What is flutter and why should i care?
What is flutter and why should i care?Sergi Martínez
 
What is flutter and why should i care? Lightning talk
What is flutter and why should i care? Lightning talkWhat is flutter and why should i care? Lightning talk
What is flutter and why should i care? Lightning talkSergi Martínez
 
Let’s talk about star wars with Dialog Flow
Let’s talk about star wars with Dialog FlowLet’s talk about star wars with Dialog Flow
Let’s talk about star wars with Dialog FlowSergi Martínez
 
Database handling with room
Database handling with roomDatabase handling with room
Database handling with roomSergi Martínez
 
Creating multillingual apps for android
Creating multillingual apps for androidCreating multillingual apps for android
Creating multillingual apps for androidSergi Martínez
 
Píldoras android i. Intro - 2ª parte
Píldoras android i. Intro - 2ª partePíldoras android i. Intro - 2ª parte
Píldoras android i. Intro - 2ª parteSergi Martínez
 

More from Sergi Martínez (8)

Kotlin, a modern language for modern times
Kotlin, a modern language for modern timesKotlin, a modern language for modern times
Kotlin, a modern language for modern times
 
What is flutter and why should i care?
What is flutter and why should i care?What is flutter and why should i care?
What is flutter and why should i care?
 
What is flutter and why should i care? Lightning talk
What is flutter and why should i care? Lightning talkWhat is flutter and why should i care? Lightning talk
What is flutter and why should i care? Lightning talk
 
Let’s talk about star wars with Dialog Flow
Let’s talk about star wars with Dialog FlowLet’s talk about star wars with Dialog Flow
Let’s talk about star wars with Dialog Flow
 
Database handling with room
Database handling with roomDatabase handling with room
Database handling with room
 
Smartphones
SmartphonesSmartphones
Smartphones
 
Creating multillingual apps for android
Creating multillingual apps for androidCreating multillingual apps for android
Creating multillingual apps for android
 
Píldoras android i. Intro - 2ª parte
Píldoras android i. Intro - 2ª partePíldoras android i. Intro - 2ª parte
Píldoras android i. Intro - 2ª parte
 

Recently uploaded

Android Application Components with Implementation & Examples
Android Application Components with Implementation & ExamplesAndroid Application Components with Implementation & Examples
Android Application Components with Implementation & ExamplesChandrakantDivate1
 
Mobile Application Development-Android and It’s Tools
Mobile Application Development-Android and It’s ToolsMobile Application Development-Android and It’s Tools
Mobile Application Development-Android and It’s ToolsChandrakantDivate1
 
Satara Call girl escort *74796//13122* Call me punam call girls 24*7hour avai...
Satara Call girl escort *74796//13122* Call me punam call girls 24*7hour avai...Satara Call girl escort *74796//13122* Call me punam call girls 24*7hour avai...
Satara Call girl escort *74796//13122* Call me punam call girls 24*7hour avai...nishasame66
 
Leading Mobile App Development Companies in India (2).pdf
Leading Mobile App Development Companies in India (2).pdfLeading Mobile App Development Companies in India (2).pdf
Leading Mobile App Development Companies in India (2).pdfCWS Technology
 
Mobile Application Development-Components and Layouts
Mobile Application Development-Components and LayoutsMobile Application Development-Components and Layouts
Mobile Application Development-Components and LayoutsChandrakantDivate1
 

Recently uploaded (6)

Android Application Components with Implementation & Examples
Android Application Components with Implementation & ExamplesAndroid Application Components with Implementation & Examples
Android Application Components with Implementation & Examples
 
Mobile Application Development-Android and It’s Tools
Mobile Application Development-Android and It’s ToolsMobile Application Development-Android and It’s Tools
Mobile Application Development-Android and It’s Tools
 
Obat Penggugur Kandungan Di Apotik Kimia Farma (087776558899)
Obat Penggugur Kandungan Di Apotik Kimia Farma (087776558899)Obat Penggugur Kandungan Di Apotik Kimia Farma (087776558899)
Obat Penggugur Kandungan Di Apotik Kimia Farma (087776558899)
 
Satara Call girl escort *74796//13122* Call me punam call girls 24*7hour avai...
Satara Call girl escort *74796//13122* Call me punam call girls 24*7hour avai...Satara Call girl escort *74796//13122* Call me punam call girls 24*7hour avai...
Satara Call girl escort *74796//13122* Call me punam call girls 24*7hour avai...
 
Leading Mobile App Development Companies in India (2).pdf
Leading Mobile App Development Companies in India (2).pdfLeading Mobile App Development Companies in India (2).pdf
Leading Mobile App Development Companies in India (2).pdf
 
Mobile Application Development-Components and Layouts
Mobile Application Development-Components and LayoutsMobile Application Development-Components and Layouts
Mobile Application Development-Components and Layouts
 

Realm or: How I learned to stop worrying and love my app database

  • 2. Sergi Martínez Android Developer at Schibsted Spain Android GDE @sergiandreplace
  • 3. The usual stuff My big server My big database My mobile app My little database My nice API The internet!
  • 4. The usual stuff My big server My big database My mobile app My little database My nice API The internet! This tries to mimic this
  • 5. The usual stuff My big server My big database My mobile app My little database My nice API The internet! Here We only need to cache entities
  • 8. SQLite SQL language Relationships Non-java data types SQL Queries SQL stuff Do we need these?
  • 9. SQLite SQL language Relationships Non-java data types SQL Queries SQL stuff Do we need these? Really?
  • 14. Also... SQLDbHelper SQL Queries Content Providers Loaders etc Boilerplate Boilerplate OH! Wow! So much boilerplate “Hard” to create. Excessive coupling with UI
  • 15. Also... SQLDbHelper SQL Queries Content Providers Loaders etc Boilerplate Boilerplate OH! Wow! So much boilerplate “Hard” to create. Excessive coupling with UI Probably… more boilerplate
  • 16. Let’s try something different… Realm It stores objects Hierarchical relationships (sort of) No boilerplate (just probably mappers) Fast! Reduces dev time drastically
  • 17. Adding Realm to your project Your project build.gradle buildscript { repositories { jcenter() } dependencies { classpath "io.realm:realm-gradle-plugin:0.89.0" } } apply plugin: 'realm-android' Your app build.gradle
  • 18. Realm Objects public class Minion extends RealmObject { private String name; private int eyes; private boolean goggles; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getEyes() { return eyes; } public void setEyes(int eyes) { this.eyes = eyes; } public boolean hasGoggles() { return goggles; } public void setGoggles(boolean goggles) { this.goggles = goggles; } }
  • 19. Realm Objects public class Minion extends RealmObject { private String name; private int eyes; private boolean goggles; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getEyes() { return eyes; } public void setEyes(int eyes) { this.eyes = eyes; } public boolean hasGoggles() { return goggles; } public void setGoggles(boolean goggles) { this.goggles = goggles; } } Must extend RealmObject
  • 20. Realm Objects public class Minion extends RealmObject { private String name; private int eyes; private boolean goggles; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getEyes() { return eyes; } public void setEyes(int eyes) { this.eyes = eyes; } public boolean hasGoggles() { return goggles; } public void setGoggles(boolean goggles) { this.goggles = goggles; } } Must extend RealmObject Not exactly true since last thursday (#$%@!). More later...
  • 21. Realm Objects public class Minion extends RealmObject { private String name; private int eyes; private boolean goggles; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getEyes() { return eyes; } public void setEyes(int eyes) { this.eyes = eyes; } public boolean hasGoggles() { return goggles; } public void setGoggles(boolean goggles) { this.goggles = goggles; } } Object members that will be stored More on types later
  • 22. Realm Objects public class Minion extends RealmObject { private String name; private int eyes; private boolean goggles; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getEyes() { return eyes; } public void setEyes(int eyes) { this.eyes = eyes; } public boolean hasGoggles() { return goggles; } public void setGoggles(boolean goggles) { this.goggles = goggles; } } Usual getters and setters
  • 24. Storing an object realm.beginTransaction(); Minion minion = realm.createObject(Minion.class); minion.setName("Bob"); minion.setEyes(1); minion.setGoggles(true); realm.commitTransaction(); realm.cancelTransaction(); or First, we start a transaction
  • 25. Storing an object realm.beginTransaction(); Minion minion = realm.createObject(Minion.class); minion.setName("Bob"); minion.setEyes(1); minion.setGoggles(true); realm.commitTransaction(); realm.cancelTransaction(); or Then we create an instance inside our realm
  • 26. Storing an object realm.beginTransaction(); Minion minion = realm.createObject(Minion.class); minion.setName("Bob"); minion.setEyes(1); minion.setGoggles(true); realm.commitTransaction(); realm.cancelTransaction(); or We set the values
  • 27. Storing an object realm.beginTransaction(); Minion minion = realm.createObject(Minion.class); minion.setName("Bob"); minion.setEyes(1); minion.setGoggles(true); realm.commitTransaction(); realm.cancelTransaction(); or And commit the transaction. Then, our changes are saved
  • 28. Storing an object realm.beginTransaction(); Minion minion = realm.createObject(Minion.class); minion.setName("Bob"); minion.setEyes(1); minion.setGoggles(true); realm.commitTransaction(); realm.cancelTransaction(); or Or we cancel the transaction and the new object is discarded
  • 29. Storing an object - II Minion minion = new Minion(); minion.setName("Bob"); minion.setEyes(1); minion.setGoggles(true); realm.beginTransaction(); realm.copyToRealm(minion); realm.commitTransaction(); Another way. We create the object outside the realm
  • 30. Storing an object - II Minion minion = new Minion(); minion.setName("Bob"); minion.setEyes(1); minion.setGoggles(true); realm.beginTransaction(); realm.copyToRealm(minion); realm.commitTransaction(); Then, we begin a transaction, copy the object into the realm, and commit
  • 31. Obtaining your Realm First, create your Realm configuration RealmConfiguration config = new RealmConfiguration.Builder(context) .name("myrealm.realm") .encryptionKey(getKey()) .schemaVersion(42) .setModules(new MySchemaModule()) .migration(new MyMigration()) .build();
  • 32. Obtaining your Realm Then, get an instance RealmConfiguration config = new RealmConfiguration.Builder(context) .name("myrealm.realm") .encryptionKey(getKey()) .schemaVersion(42) .setModules(new MySchemaModule()) .migration(new MyMigration()) .build(); Realm myRealm = Realm.getInstance(config);
  • 33. Obtaining your Realm Or use the default Realm Instance RealmConfiguration config = new RealmConfiguration.Builder(context) .name("myrealm.realm") .encryptionKey(getKey()) .schemaVersion(42) .setModules(new MySchemaModule()) .migration(new MyMigration()) .build(); Realm.setDefaultConfiguration(config); And obtain it anywhere Realm realm = Realm.getDefaultInstance(); // Stuff realm.close();
  • 34. Close your Realms For each Realm.getDefaultInstance() or Realm.getInstance() you must execute realm.close() at the end
  • 35. Querying a Realm Realm uses fluent syntax. Just create a RealmQuery object based on the Realm class you want RealmQuery<Minion> query = realm.where(Minion.class); Add operations and filters and execute RealmResults<Minion> results = query.equalTo(“name”, “Bob”).findAll(); Do something with the result for (Minion minion:results) { …. //Do stuff }
  • 38. Relationships - 1:N Just have a RealmObject with a RealmObject public class Minion extends RealmObject { private String name; private int eyes; private boolean goggles; private Banana banana //Getters, setters and so on } Public class Banana extends RealmObject { … }
  • 39. Storing 1:N related objects realm.beginTransaction() Banana banana = realm.createObject(Banana.class); banana.setSomething… Minion minion = realm.createObject(Minion.class); minion.setName(“Bob”); minion.setBanana(banana); realm.writeTransaction();
  • 40. Relationships - M:N Just have a RealmObject with a List<? extends RealmObject> public class Minion extends RealmObject { private String name; private int eyes; private boolean goggles; private RealmList<Banana> bananas //Getters, setters and so on } Public class Banana extends RealmObject { … }
  • 41. Storing M:N related objects realm.beginTransaction() Banana banana = realm.createObject(Banana.class); banana.setSomething… Minion minion = realm.createObject(Minion.class); minion.setName(“Bob”); minion.getBananas().add(banana); realm.writeTransaction();
  • 42. Querying M:N related objects RealmResults<Minion> minions = realm.where(Minions.class) .equalTo("banana.size", "big") .findAll();
  • 43. Threading Each Realm should live in the same Thread is has been created You can’t pass Realms between threads Realms are automatically updated between threads IF they are in threads with a Looper Otherwise… Realm.refresh()
  • 45. Brand new changes This week on Realm: RealmModel interface + static methods RealmCollection/RealmOrderedCollection Interfaces Primary keys can be null!
  • 46. How I use it public abstract class VOBaseMapper<V extends RealmObject,E> { public abstract V toVO(E entity); public abstract E toEntity(V vo) ; public RealmList<V> toVO(List<E> entities) { RealmList<V> realmList=new RealmList<V>(); for (E entity:entities) { realmList.add(toVO(entity)); } return realmList; }
  • 47. How I use it public List<E> toEntity(RealmList<V> vos) { List<E> applicationEntityList = new ArrayList<>(); for(V vo :vos){ applicationEntityList.add(toEntity(vo)); } return applicationEntityList; } public List<E> toEntity(RealmResults<V> vos) { List<E> applicationEntityList = new ArrayList<>(); for(V vo :vos){ applicationEntityList.add(toEntity(vo)); } return applicationEntityList; } }
  • 48. How I use it public class UserVOMapper extends VOBaseMapper<UserVO,User > { private User user; @Override public UserVO toVO(User user) { UserVO vo=new UserVO(); vo.setName(user.name); vo.setEmail(user.email); return vo; } @Override public User toEntity(UserVO vo) { User user= new User(); user.name=vo.getName(); user.email=vo.getEmail(); return user; } }
  • 49. And that’s not all But enough for today. Questions?