SlideShare a Scribd company logo
1 of 20
Realm Mobile Database
Geetika Gupta
Software Consultant
Knoldus Software LLP
AGENDA
➔
What is Realm
➔
Installation
➔
Realm Models
➔
Writes
➔
Queries
➔
Configuring Realm
What is Realm ?
➔
Realm is a cross-platform mobile database, released in July, 2014.
➔
It is a data persistence solution designed specifically for mobile applications.
➔
Realm store data in a universal, table-based format
➔
It is simple as data is directly exposed as objects and queryable by code, removing
the need for ORM's maintenance issues.
➔
Realm is faster than raw SQLite on common operations, while maintaining an
extremely rich feature set.
Installation
➔
You can install realm by adding the following class path dependency to the project
level build.gradle file.
buildscript {
repositories {
jcenter()
}
dependencies {
compile 'io.realm:realm-android:0.87.4'
}
}
Models
➔
Realm model classes are created by extending the RealmObject base class.
public class User extends RealmObject {
private String name;
private int age;
}
➔
Realm supports the following field types:
boolean, byte, short, int, long, float, double, String, Date and byte[].
The integer types byte, short, int, and long are all mapped to the same type (long)
within Realm.
➔
Each model class that extends RealmObject describes the schema for the table in
Realm.
Indexing Properties
➔ The annotation @Index will add a search index to the field.
➔ It supports indexing on the following fields: String, byte, short, Int, long,
boolean and Date
Primary Keys
➔ @PrimaryKey will make the field primary key.
➔ It supports string or Integer (byte, short, int, or long) as primary keys.
➔ @PrimaryKey field implicitly sets the annotation @Index.
➔ copyToRealmOrUpdate() method is used to update an object having primary
key.
➔ It looks for an existing object with the primary key and update it if found, If
no object is found a new object is created.
➔ Calling copyToRealmOrUpdate() on classes without primary keys will throw
an exception.
Transaction Blocks
➔
realm.beginTransaction(): Starts a transaction
➔
realm.commitTransaction(): Commits a transaction, all the changes made will be
written to disk
➔
realm.cancelTransaction(): Cancels a transaction and all the changes will be
discarded.
➔
realm.executeTransaction(): Automatically handles begin/commit, and cancel if an
error happens.
➔
Eg. 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");
}
});
Writes
➔
A write transaction is a transaction that is performed to update the state of your realm
object
➔
All write operations (adding, modifying, and removing objects) must be wrapped in
write transactions.
➔
Using write transactions, your data will always be in a consistent state.
➔
A write transaction can either be committed or cancelled. During the commit, all
changes will be written to disk, and the commit will only succeed if all changes can be
persisted
Eg. realm.beginTransaction();
//... add or update objects here ...
realm.commitTransaction();
Writes (cont...)
➔
Realm.executeTransaction() is a method that lets you exclude the begin() and
commit() transaction steps as it handles it internally.
➔
If some Exception occurs inside a transaction, then you need to cancel that
transaction in the catch block
➔
Using executeTransaction() you don’t need to call cancel transaction explicitly, it is
done automatically.
Creating Objects
➔
RealmObjects are strongly tied to a Realm, they should be instantiated through the
Realm directly:
Eg. realm.beginTransaction();
User user = realm.createObject(User.class); // Create a new object
user.setName("John");
user.setEmail("john@corporation.com");
realm.commitTransaction();
➔
It can also be created using realm.copyToRealm(). You can create an instance of an
object first and add it later.
Eg. User user = new User("John");
user.setEmail("john@corporation.com");
// Copy the object to Realm. Any further changes must happen on realmUser
realm.beginTransaction();
User realmUser = realm.copyToRealm(user);
realm.commitTransaction();
➔
When using realm.copyToRealm(), only the returned object is managed by Realm, so
any further changes should be made to returned object.
Auto Updating Objects
RealmObjects are live and auto-updating. Modifying objects that affect the query will
be reflected in the results immediately.
realm.executeTransaction(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
Dog myDog = realm.createObject(Dog.class);
myDog.setName("Fido");
myDog.setAge(1);
}
});
Dog myDog = realm.where(Dog.class).equalTo("age", 1).findFirst();
realm.executeTransaction(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
Dog myPuppy = realm.where(Dog.class).equalTo("age",
1).findFirst();
myPuppy.setAge(2);
}
});
myDog.getAge(); // => 2
Asynchronous Transactions
➔
By using an Asynchronous Transaction, Realm will execute that transaction on the
background thread.
➔
Callbacks can be provided for successful or failure conditions.
Eg. realm.executeTransactionAsync(new Realm.Transaction() {
@Override
public void execute(Realm bgRealm) {
User user = bgRealm.createObject(User.class);
user.setName("John");
user.setEmail("john@corporation.com");
}
}, new Realm.Transaction.OnSuccess() {
@Override
public void onSuccess() {
// Transaction was a success.
}
}, new Realm.Transaction.OnError() {
@Override
public void onError(Throwable error) {
// Transaction failed and was automatically canceled.
}
});
Queries
➔
The following conditions are supported:
between(), greaterThan(), lessThan(), greaterThanOrEqualTo() &
lessThanOrEqualTo()
equalTo() & notEqualTo()
contains(), beginsWith() & endsWith()
isNull() & isNotNull()
isEmpty() & isNotEmpty()
➔
You can also group conditions with “parentheses” to specify order of evaluation:
beginGroup() is your “left parenthesis” and endGroup() your “right parenthesis”:
Eg.
RealmResults<User> r = realm.where(User.class)
.greaterThan("age", 10) //implicit AND
.beginGroup()
.equalTo("name", "Peter")
.or()
.contains("name", "Jo")
.endGroup()
.findAll();
Aggregation Queries
➔
A RealmResults has various aggregation methods:
RealmResults<User> results = realm.where(User.class).findAll();
long sum = results.sum("age").longValue();
long min = results.min("age").longValue();
long max = results.max("age").longValue();
double average = results.average("age");
long matches = results.size();
Deletion Queries
➔ You can delete the results of a query from the Realm:
RealmResults<Dog> results = realm.where(Dog.class).findAll();
// All changes to data must happen in a transaction
realm.executeTransaction(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
results.removeLast(); // remove last object
results.remove(5); // remove a single object
Dog dog = results.get(2);
results.remove(dog);
}
});
Configuring Realm
➔
Realms are equivalent of a database: they contain different kinds of objects.
➔
RealmConfiguration object is used to control all aspects of how a Realm is created.
The minimal configuration usable by Realm is:
RealmConfiguration config = new RealmConfiguration.Builder().build();
The above configuration will point to a file calles default.realm
➔ The RealmConfiguration can be saved as a default configuration.
public class MyActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Realm realm = Realm.getDefaultInstance();
// ... Do something ...
realm.close();
}
}
In Memory Realm
➔
To define an instance for an un-persisted in-memory Realm:
RealmConfiguration myConfig = new RealmConfiguration.Builder()
.name("myrealm.realm")
.inMemory()
.build();
Realm.getInstance(config);
Setting this will create an in-memory Realm instead of saving it to disk.
In-memory Realms might still use disk space if memory is running low, but all files
created by an in-memory Realm will be deleted when the Realm is closed.
DEMO
➔ Github Repository: RealmBookApplication
➔
Realm documentation
➔
Github Repository: Realm-Java
References
Thank You :)

More Related Content

What's hot

Кирилл Безпалый, .NET Developer, Ciklum
Кирилл Безпалый, .NET Developer, CiklumКирилл Безпалый, .NET Developer, Ciklum
Кирилл Безпалый, .NET Developer, Ciklum
Alina Vilk
 
Share pointtechies linqtosp-andsbs
Share pointtechies linqtosp-andsbsShare pointtechies linqtosp-andsbs
Share pointtechies linqtosp-andsbs
Shakir Majeed Khan
 
AWS IoT 핸즈온 워크샵 - 실습 4. Device Failure 상황 처리하기 (김무현 솔루션즈 아키텍트)
AWS IoT 핸즈온 워크샵 - 실습 4. Device Failure 상황 처리하기 (김무현 솔루션즈 아키텍트)AWS IoT 핸즈온 워크샵 - 실습 4. Device Failure 상황 처리하기 (김무현 솔루션즈 아키텍트)
AWS IoT 핸즈온 워크샵 - 실습 4. Device Failure 상황 처리하기 (김무현 솔루션즈 아키텍트)
Amazon Web Services Korea
 
Sharepoint Saturday India Online best practice for developing share point sol...
Sharepoint Saturday India Online best practice for developing share point sol...Sharepoint Saturday India Online best practice for developing share point sol...
Sharepoint Saturday India Online best practice for developing share point sol...
Shakir Majeed Khan
 
How i wrote my own bdd framework
How i wrote my own bdd frameworkHow i wrote my own bdd framework
How i wrote my own bdd framework
Mark Maglana
 

What's hot (20)

iOS Dev Happy Hour Realm - Feb 2021
iOS Dev Happy Hour Realm - Feb 2021iOS Dev Happy Hour Realm - Feb 2021
iOS Dev Happy Hour Realm - Feb 2021
 
Let's Redux!
Let's Redux!Let's Redux!
Let's Redux!
 
CocoaHeads PDX 2014 01 23 : CoreData and iCloud Improvements iOS7 / OSX Maver...
CocoaHeads PDX 2014 01 23 : CoreData and iCloud Improvements iOS7 / OSX Maver...CocoaHeads PDX 2014 01 23 : CoreData and iCloud Improvements iOS7 / OSX Maver...
CocoaHeads PDX 2014 01 23 : CoreData and iCloud Improvements iOS7 / OSX Maver...
 
State Models for React with Redux
State Models for React with ReduxState Models for React with Redux
State Models for React with Redux
 
Client Server Communication on iOS
Client Server Communication on iOSClient Server Communication on iOS
Client Server Communication on iOS
 
MongoDB .local London 2019: Realm: The Secret Sauce for Better Mobile Apps
MongoDB .local London 2019: Realm: The Secret Sauce for Better Mobile AppsMongoDB .local London 2019: Realm: The Secret Sauce for Better Mobile Apps
MongoDB .local London 2019: Realm: The Secret Sauce for Better Mobile Apps
 
Building React Applications with Redux
Building React Applications with ReduxBuilding React Applications with Redux
Building React Applications with Redux
 
Кирилл Безпалый, .NET Developer, Ciklum
Кирилл Безпалый, .NET Developer, CiklumКирилл Безпалый, .NET Developer, Ciklum
Кирилл Безпалый, .NET Developer, Ciklum
 
React JS and why it's awesome
React JS and why it's awesomeReact JS and why it's awesome
React JS and why it's awesome
 
Slick eventsourcing
Slick eventsourcingSlick eventsourcing
Slick eventsourcing
 
ProvJS: Six Months of ReactJS and Redux
ProvJS:  Six Months of ReactJS and ReduxProvJS:  Six Months of ReactJS and Redux
ProvJS: Six Months of ReactJS and Redux
 
Intro to Core Data
Intro to Core DataIntro to Core Data
Intro to Core Data
 
Share pointtechies linqtosp-andsbs
Share pointtechies linqtosp-andsbsShare pointtechies linqtosp-andsbs
Share pointtechies linqtosp-andsbs
 
Query service in vCloud Director
Query service in vCloud DirectorQuery service in vCloud Director
Query service in vCloud Director
 
AWS IoT 핸즈온 워크샵 - 실습 4. Device Failure 상황 처리하기 (김무현 솔루션즈 아키텍트)
AWS IoT 핸즈온 워크샵 - 실습 4. Device Failure 상황 처리하기 (김무현 솔루션즈 아키텍트)AWS IoT 핸즈온 워크샵 - 실습 4. Device Failure 상황 처리하기 (김무현 솔루션즈 아키텍트)
AWS IoT 핸즈온 워크샵 - 실습 4. Device Failure 상황 처리하기 (김무현 솔루션즈 아키텍트)
 
Kubernetes Operators With Scala
Kubernetes Operators With ScalaKubernetes Operators With Scala
Kubernetes Operators With Scala
 
Actor Model Akka Framework
Actor Model Akka FrameworkActor Model Akka Framework
Actor Model Akka Framework
 
Sharepoint Saturday India Online best practice for developing share point sol...
Sharepoint Saturday India Online best practice for developing share point sol...Sharepoint Saturday India Online best practice for developing share point sol...
Sharepoint Saturday India Online best practice for developing share point sol...
 
Distributed Eventing in OSGi
Distributed Eventing in OSGiDistributed Eventing in OSGi
Distributed Eventing in OSGi
 
How i wrote my own bdd framework
How i wrote my own bdd frameworkHow i wrote my own bdd framework
How i wrote my own bdd framework
 

Viewers also liked

Viewers also liked (20)

Why realm?
Why realm?Why realm?
Why realm?
 
Drilling the Async Library
Drilling the Async LibraryDrilling the Async Library
Drilling the Async Library
 
Getting Started With AureliaJs
Getting Started With AureliaJsGetting Started With AureliaJs
Getting Started With AureliaJs
 
Introduction to Scala JS
Introduction to Scala JSIntroduction to Scala JS
Introduction to Scala JS
 
Akka streams
Akka streamsAkka streams
Akka streams
 
String interpolation
String interpolationString interpolation
String interpolation
 
Mailchimp and Mandrill - The ‘Hominidae’ kingdom
Mailchimp and Mandrill - The ‘Hominidae’ kingdomMailchimp and Mandrill - The ‘Hominidae’ kingdom
Mailchimp and Mandrill - The ‘Hominidae’ kingdom
 
Shapeless- Generic programming for Scala
Shapeless- Generic programming for ScalaShapeless- Generic programming for Scala
Shapeless- Generic programming for Scala
 
Kanban
KanbanKanban
Kanban
 
Introduction to Java 8
Introduction to Java 8Introduction to Java 8
Introduction to Java 8
 
Introduction to Scala Macros
Introduction to Scala MacrosIntroduction to Scala Macros
Introduction to Scala Macros
 
An Introduction to Quill
An Introduction to QuillAn Introduction to Quill
An Introduction to Quill
 
Mandrill Templates
Mandrill TemplatesMandrill Templates
Mandrill Templates
 
ANTLR4 and its testing
ANTLR4 and its testingANTLR4 and its testing
ANTLR4 and its testing
 
Functors, Applicatives and Monads In Scala
Functors, Applicatives and Monads In ScalaFunctors, Applicatives and Monads In Scala
Functors, Applicatives and Monads In Scala
 
Introduction to ScalaZ
Introduction to ScalaZIntroduction to ScalaZ
Introduction to ScalaZ
 
Effective way to code in Scala
Effective way to code in ScalaEffective way to code in Scala
Effective way to code in Scala
 
Introduction to Knockout Js
Introduction to Knockout JsIntroduction to Knockout Js
Introduction to Knockout Js
 
HTML5, CSS, JavaScript Style guide and coding conventions
HTML5, CSS, JavaScript Style guide and coding conventionsHTML5, CSS, JavaScript Style guide and coding conventions
HTML5, CSS, JavaScript Style guide and coding conventions
 
Functional programming in Javascript
Functional programming in JavascriptFunctional programming in Javascript
Functional programming in Javascript
 

Similar to Realm Mobile Database - An Introduction

Joe Walker Interactivewebsites Cometand Dwr
Joe Walker Interactivewebsites Cometand DwrJoe Walker Interactivewebsites Cometand Dwr
Joe Walker Interactivewebsites Cometand Dwr
deimos
 
Ajax Fundamentals Web Applications
Ajax Fundamentals Web ApplicationsAjax Fundamentals Web Applications
Ajax Fundamentals Web Applications
dominion
 
ASP.Net Presentation Part2
ASP.Net Presentation Part2ASP.Net Presentation Part2
ASP.Net Presentation Part2
Neeraj Mathur
 
Unit test candidate solutions
Unit test candidate solutionsUnit test candidate solutions
Unit test candidate solutions
benewu
 

Similar to Realm Mobile Database - An Introduction (20)

Painless Persistence with Realm
Painless Persistence with RealmPainless Persistence with Realm
Painless Persistence with Realm
 
Realm Java 2.2.0: Build better apps, faster apps
Realm Java 2.2.0: Build better apps, faster appsRealm Java 2.2.0: Build better apps, faster apps
Realm Java 2.2.0: Build better apps, faster 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
 
Angular JS2 Training Session #1
Angular JS2 Training Session #1Angular JS2 Training Session #1
Angular JS2 Training Session #1
 
ReactJS
ReactJSReactJS
ReactJS
 
Secrets of JavaScript Libraries
Secrets of JavaScript LibrariesSecrets of JavaScript Libraries
Secrets of JavaScript Libraries
 
Reactивная тяга
Reactивная тягаReactивная тяга
Reactивная тяга
 
Deep Dumpster Diving
Deep Dumpster DivingDeep Dumpster Diving
Deep Dumpster Diving
 
The Theory Of The Dom
The Theory Of The DomThe Theory Of The Dom
The Theory Of The Dom
 
Joe Walker Interactivewebsites Cometand Dwr
Joe Walker Interactivewebsites Cometand DwrJoe Walker Interactivewebsites Cometand Dwr
Joe Walker Interactivewebsites Cometand Dwr
 
Ember.js - A JavaScript framework for creating ambitious web applications
Ember.js - A JavaScript framework for creating ambitious web applications  Ember.js - A JavaScript framework for creating ambitious web applications
Ember.js - A JavaScript framework for creating ambitious web applications
 
Painless Persistence in a Disconnected World
Painless Persistence in a Disconnected WorldPainless Persistence in a Disconnected World
Painless Persistence in a Disconnected World
 
Building AOL's High Performance, Enterprise Wide Mail Application With Silver...
Building AOL's High Performance, Enterprise Wide Mail Application With Silver...Building AOL's High Performance, Enterprise Wide Mail Application With Silver...
Building AOL's High Performance, Enterprise Wide Mail Application With Silver...
 
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
 
eXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction TrainingeXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction Training
 
Ajax Fundamentals Web Applications
Ajax Fundamentals Web ApplicationsAjax Fundamentals Web Applications
Ajax Fundamentals Web Applications
 
Presentation - Windows App Development - II - Mr. Chandan Gupta
Presentation - Windows App Development - II - Mr. Chandan GuptaPresentation - Windows App Development - II - Mr. Chandan Gupta
Presentation - Windows App Development - II - Mr. Chandan Gupta
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotation
 
ASP.Net Presentation Part2
ASP.Net Presentation Part2ASP.Net Presentation Part2
ASP.Net Presentation Part2
 
Unit test candidate solutions
Unit test candidate solutionsUnit test candidate solutions
Unit test candidate solutions
 

More from Knoldus Inc.

More from Knoldus Inc. (20)

Supply chain security with Kubeclarity.pptx
Supply chain security with Kubeclarity.pptxSupply chain security with Kubeclarity.pptx
Supply chain security with Kubeclarity.pptx
 
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML ParsingMastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
 
Akka gRPC Essentials A Hands-On Introduction
Akka gRPC Essentials A Hands-On IntroductionAkka gRPC Essentials A Hands-On Introduction
Akka gRPC Essentials A Hands-On Introduction
 
Entity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptxEntity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptx
 
Introduction to Redis and its features.pptx
Introduction to Redis and its features.pptxIntroduction to Redis and its features.pptx
Introduction to Redis and its features.pptx
 
GraphQL with .NET Core Microservices.pdf
GraphQL with .NET Core Microservices.pdfGraphQL with .NET Core Microservices.pdf
GraphQL with .NET Core Microservices.pdf
 
NuGet Packages Presentation (DoT NeT).pptx
NuGet Packages Presentation (DoT NeT).pptxNuGet Packages Presentation (DoT NeT).pptx
NuGet Packages Presentation (DoT NeT).pptx
 
Data Quality in Test Automation Navigating the Path to Reliable Testing
Data Quality in Test Automation Navigating the Path to Reliable TestingData Quality in Test Automation Navigating the Path to Reliable Testing
Data Quality in Test Automation Navigating the Path to Reliable Testing
 
K8sGPTThe AI​ way to diagnose Kubernetes
K8sGPTThe AI​ way to diagnose KubernetesK8sGPTThe AI​ way to diagnose Kubernetes
K8sGPTThe AI​ way to diagnose Kubernetes
 
Introduction to Circle Ci Presentation.pptx
Introduction to Circle Ci Presentation.pptxIntroduction to Circle Ci Presentation.pptx
Introduction to Circle Ci Presentation.pptx
 
Robusta -Tool Presentation (DevOps).pptx
Robusta -Tool Presentation (DevOps).pptxRobusta -Tool Presentation (DevOps).pptx
Robusta -Tool Presentation (DevOps).pptx
 
Optimizing Kubernetes using GOLDILOCKS.pptx
Optimizing Kubernetes using GOLDILOCKS.pptxOptimizing Kubernetes using GOLDILOCKS.pptx
Optimizing Kubernetes using GOLDILOCKS.pptx
 
Azure Function App Exception Handling.pptx
Azure Function App Exception Handling.pptxAzure Function App Exception Handling.pptx
Azure Function App Exception Handling.pptx
 
CQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptxCQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptx
 
ETL Observability: Azure to Snowflake Presentation
ETL Observability: Azure to Snowflake PresentationETL Observability: Azure to Snowflake Presentation
ETL Observability: Azure to Snowflake Presentation
 
Scripting with K6 - Beyond the Basics Presentation
Scripting with K6 - Beyond the Basics PresentationScripting with K6 - Beyond the Basics Presentation
Scripting with K6 - Beyond the Basics Presentation
 
Getting started with dotnet core Web APIs
Getting started with dotnet core Web APIsGetting started with dotnet core Web APIs
Getting started with dotnet core Web APIs
 
Introduction To Rust part II Presentation
Introduction To Rust part II PresentationIntroduction To Rust part II Presentation
Introduction To Rust part II Presentation
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
Configuring Workflows & Validators in JIRA
Configuring Workflows & Validators in JIRAConfiguring Workflows & Validators in JIRA
Configuring Workflows & Validators in JIRA
 

Recently uploaded

CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
VishalKumarJha10
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
VictorSzoltysek
 

Recently uploaded (20)

VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
ManageIQ - Sprint 236 Review - Slide Deck
ManageIQ - Sprint 236 Review - Slide DeckManageIQ - Sprint 236 Review - Slide Deck
ManageIQ - Sprint 236 Review - Slide Deck
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verifiedSector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
 
LEVEL 5 - SESSION 1 2023 (1).pptx - PDF 123456
LEVEL 5   - SESSION 1 2023 (1).pptx - PDF 123456LEVEL 5   - SESSION 1 2023 (1).pptx - PDF 123456
LEVEL 5 - SESSION 1 2023 (1).pptx - PDF 123456
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 

Realm Mobile Database - An Introduction

  • 1. Realm Mobile Database Geetika Gupta Software Consultant Knoldus Software LLP
  • 2. AGENDA ➔ What is Realm ➔ Installation ➔ Realm Models ➔ Writes ➔ Queries ➔ Configuring Realm
  • 3. What is Realm ? ➔ Realm is a cross-platform mobile database, released in July, 2014. ➔ It is a data persistence solution designed specifically for mobile applications. ➔ Realm store data in a universal, table-based format ➔ It is simple as data is directly exposed as objects and queryable by code, removing the need for ORM's maintenance issues. ➔ Realm is faster than raw SQLite on common operations, while maintaining an extremely rich feature set.
  • 4. Installation ➔ You can install realm by adding the following class path dependency to the project level build.gradle file. buildscript { repositories { jcenter() } dependencies { compile 'io.realm:realm-android:0.87.4' } }
  • 5. Models ➔ Realm model classes are created by extending the RealmObject base class. public class User extends RealmObject { private String name; private int age; } ➔ Realm supports the following field types: boolean, byte, short, int, long, float, double, String, Date and byte[]. The integer types byte, short, int, and long are all mapped to the same type (long) within Realm. ➔ Each model class that extends RealmObject describes the schema for the table in Realm.
  • 6. Indexing Properties ➔ The annotation @Index will add a search index to the field. ➔ It supports indexing on the following fields: String, byte, short, Int, long, boolean and Date
  • 7. Primary Keys ➔ @PrimaryKey will make the field primary key. ➔ It supports string or Integer (byte, short, int, or long) as primary keys. ➔ @PrimaryKey field implicitly sets the annotation @Index. ➔ copyToRealmOrUpdate() method is used to update an object having primary key. ➔ It looks for an existing object with the primary key and update it if found, If no object is found a new object is created. ➔ Calling copyToRealmOrUpdate() on classes without primary keys will throw an exception.
  • 8. Transaction Blocks ➔ realm.beginTransaction(): Starts a transaction ➔ realm.commitTransaction(): Commits a transaction, all the changes made will be written to disk ➔ realm.cancelTransaction(): Cancels a transaction and all the changes will be discarded. ➔ realm.executeTransaction(): Automatically handles begin/commit, and cancel if an error happens. ➔ Eg. 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"); } });
  • 9. Writes ➔ A write transaction is a transaction that is performed to update the state of your realm object ➔ All write operations (adding, modifying, and removing objects) must be wrapped in write transactions. ➔ Using write transactions, your data will always be in a consistent state. ➔ A write transaction can either be committed or cancelled. During the commit, all changes will be written to disk, and the commit will only succeed if all changes can be persisted Eg. realm.beginTransaction(); //... add or update objects here ... realm.commitTransaction();
  • 10. Writes (cont...) ➔ Realm.executeTransaction() is a method that lets you exclude the begin() and commit() transaction steps as it handles it internally. ➔ If some Exception occurs inside a transaction, then you need to cancel that transaction in the catch block ➔ Using executeTransaction() you don’t need to call cancel transaction explicitly, it is done automatically.
  • 11. Creating Objects ➔ RealmObjects are strongly tied to a Realm, they should be instantiated through the Realm directly: Eg. realm.beginTransaction(); User user = realm.createObject(User.class); // Create a new object user.setName("John"); user.setEmail("john@corporation.com"); realm.commitTransaction(); ➔ It can also be created using realm.copyToRealm(). You can create an instance of an object first and add it later. Eg. User user = new User("John"); user.setEmail("john@corporation.com"); // Copy the object to Realm. Any further changes must happen on realmUser realm.beginTransaction(); User realmUser = realm.copyToRealm(user); realm.commitTransaction(); ➔ When using realm.copyToRealm(), only the returned object is managed by Realm, so any further changes should be made to returned object.
  • 12. Auto Updating Objects RealmObjects are live and auto-updating. Modifying objects that affect the query will be reflected in the results immediately. realm.executeTransaction(new Realm.Transaction() { @Override public void execute(Realm realm) { Dog myDog = realm.createObject(Dog.class); myDog.setName("Fido"); myDog.setAge(1); } }); Dog myDog = realm.where(Dog.class).equalTo("age", 1).findFirst(); realm.executeTransaction(new Realm.Transaction() { @Override public void execute(Realm realm) { Dog myPuppy = realm.where(Dog.class).equalTo("age", 1).findFirst(); myPuppy.setAge(2); } }); myDog.getAge(); // => 2
  • 13. Asynchronous Transactions ➔ By using an Asynchronous Transaction, Realm will execute that transaction on the background thread. ➔ Callbacks can be provided for successful or failure conditions. Eg. realm.executeTransactionAsync(new Realm.Transaction() { @Override public void execute(Realm bgRealm) { User user = bgRealm.createObject(User.class); user.setName("John"); user.setEmail("john@corporation.com"); } }, new Realm.Transaction.OnSuccess() { @Override public void onSuccess() { // Transaction was a success. } }, new Realm.Transaction.OnError() { @Override public void onError(Throwable error) { // Transaction failed and was automatically canceled. } });
  • 14. Queries ➔ The following conditions are supported: between(), greaterThan(), lessThan(), greaterThanOrEqualTo() & lessThanOrEqualTo() equalTo() & notEqualTo() contains(), beginsWith() & endsWith() isNull() & isNotNull() isEmpty() & isNotEmpty() ➔ You can also group conditions with “parentheses” to specify order of evaluation: beginGroup() is your “left parenthesis” and endGroup() your “right parenthesis”: Eg. RealmResults<User> r = realm.where(User.class) .greaterThan("age", 10) //implicit AND .beginGroup() .equalTo("name", "Peter") .or() .contains("name", "Jo") .endGroup() .findAll();
  • 15. Aggregation Queries ➔ A RealmResults has various aggregation methods: RealmResults<User> results = realm.where(User.class).findAll(); long sum = results.sum("age").longValue(); long min = results.min("age").longValue(); long max = results.max("age").longValue(); double average = results.average("age"); long matches = results.size(); Deletion Queries ➔ You can delete the results of a query from the Realm: RealmResults<Dog> results = realm.where(Dog.class).findAll(); // All changes to data must happen in a transaction realm.executeTransaction(new Realm.Transaction() { @Override public void execute(Realm realm) { results.removeLast(); // remove last object results.remove(5); // remove a single object Dog dog = results.get(2); results.remove(dog); } });
  • 16. Configuring Realm ➔ Realms are equivalent of a database: they contain different kinds of objects. ➔ RealmConfiguration object is used to control all aspects of how a Realm is created. The minimal configuration usable by Realm is: RealmConfiguration config = new RealmConfiguration.Builder().build(); The above configuration will point to a file calles default.realm ➔ The RealmConfiguration can be saved as a default configuration. public class MyActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Realm realm = Realm.getDefaultInstance(); // ... Do something ... realm.close(); } }
  • 17. In Memory Realm ➔ To define an instance for an un-persisted in-memory Realm: RealmConfiguration myConfig = new RealmConfiguration.Builder() .name("myrealm.realm") .inMemory() .build(); Realm.getInstance(config); Setting this will create an in-memory Realm instead of saving it to disk. In-memory Realms might still use disk space if memory is running low, but all files created by an in-memory Realm will be deleted when the Realm is closed.
  • 18. DEMO ➔ Github Repository: RealmBookApplication