2. REALM - A MOBILE DATABASE REPLACEMENT
PHOENIX MOBILE FESTIVAL
▸Use #phxmobi as the twitter hashtag and follow
@phxmobifestival for updates.
▸Download Phoenix Mobile Festival App (search for
'phxmobi') from AppStore or Google Play. From the app you
can create your own agenda for the day and provide
feedback on the sessions.
3. REALM - A MOBILE DATABASE REPLACEMENT
WHO AM I?
▸Android Developer at Mokriya.
▸Developing Android apps since the start (first Android phone
was the Droid)
▸Before working at Mokriya, worked for Jaybird, and a few
smaller companies
▸Self published a few apps - Spotilarm, Volume Sync, Bill
Tracker
4. REALM - A MOBILE DATABASE REPLACEMENT
WHAT IS REALM?
▸It’s a database.
▸A replacement for Sqlite.
▸It is NOT an ORM for Sqlite.
5. REALM - A MOBILE DATABASE REPLACEMENT
WHY SHOULD I USE IT?
▸Easy Setup
▸Cross Platform
▸ Android, iOS (Objective-C and Swift), Xamarin, React Native
▸FAST
6. REALM - A MOBILE DATABASE REPLACEMENT
WHO IS USING REALM?
7. REALM - A MOBILE DATABASE REPLACEMENT
FEATURES OF REALM
▸Fluent Interface
▸Field Annotations
▸Migrations
▸Encryption
▸Auto Updates and Notifications
▸RxJava Support
8. REALM - A MOBILE DATABASE REPLACEMENT
FLUENT INTERFACE
getRealm().where(Bill.class)
.equalTo("deleted", false)
.between("dueDate", new
DateTime().minusWeeks(1).toDate(), new
DateTime().plusWeeks(1).plusDays(1)
.toDate())
.findAll();
https://github.com/djrausch/BillTracker/blob/master/app/src/main/java/com/djrausch/billtracker/util/BillUtil.jav
a#L46
9. REALM - A MOBILE DATABASE REPLACEMENT
FIELD ANNOTATIONS
▸@PrimaryKey
▸Table PK
▸@Required
▸Require a value, not null
▸@Ignore
▸Do not persist field to disk
10. REALM - A MOBILE DATABASE REPLACEMENT
MIGRATIONS
public class Migration implements RealmMigration {
@Override
public void migrate(DynamicRealm realm, long oldVersion, long newVersion) {
RealmSchema schema = realm.getSchema();
if (oldVersion == 0) {
//Add pay url to bill
schema.get("Bill")
.addField("payUrl", String.class);
oldVersion++;
}…
}
}
https://github.com/djrausch/BillTracker/blob/master/app/src/main/java/com/djrausch/billtracker/models/Migration.java
11. REALM - A MOBILE DATABASE REPLACEMENT
ENCRYPTION
RealmConfiguration config = new
RealmConfiguration.Builder(context)
.encryptionKey(getKey())
.build();
Realm realm = Realm.getInstance(config);
https://realm.io/docs/java/latest/#encryption
12. REALM - A MOBILE DATABASE REPLACEMENT
AUTO UPDATES & NOTIFICATIONS
bills.addChangeListener(new RealmChangeListener<RealmResults<Bill>>() {
@Override
public void onChange(RealmResults<Bill> element) {
if (adapter.getItemCount() == 0) {
noBillsLayout.setVisibility(View.VISIBLE);
recyclerView.setVisibility(View.GONE);
} else {
noBillsLayout.setVisibility(View.GONE);
recyclerView.setVisibility(View.VISIBLE);
}
}
});
https://github.com/djrausch/BillTracker/blob/master/app/src/main/java/com/djrausch/billtracker/MainActivity.java#L132
13. REALM - A MOBILE DATABASE REPLACEMENT
RXJAVA
getRealm().where(Bill.class).contains(“uuid”, billUuid).findFirst().asObservable()
.filter(new Func1<Bill, Boolean>() {
@Override
public Boolean call(Bill bill) {
return bill.isLoaded();
}
}).subscribe(new Action1<Bill>() {
@Override
public void call(Bill bill) {
setUI(bill);
if (bill.paidDates != null) {
if (adapter == null) {
adapter = new PaidDateRecyclerViewAdapter(ViewBillDetails.this, bill.getPaidDates());
recyclerView.setLayoutManager(new LinearLayoutManager(ViewBillDetails.this));
recyclerView.setAdapter(adapter);
}
}
}
});
https://github.com/djrausch/BillTracker/blob/master/app/src/main/java/com/djrausch/billtracker/AddOrEditBillActivity.java#L109
https://realm.io/docs/java/latest/#rxjava
14. REALM - A MOBILE DATABASE REPLACEMENT
OK, SO HOW DO I USE IT?
▸There is no schema set up
▸Simply have your model classes extend RealmObject
public class Bill extends RealmObject {
@PrimaryKey
public String uuid;
public String name;
public String description;
public int repeatingType = 0;
public Date dueDate;
public String payUrl;
public RealmList<BillNote> notes;
public RealmList<BillPaid> paidDates;
public boolean deleted = false;
public int amountDue = 0;
https://github.com/djrausch/BillTracker/blob/master/app/src/main/java/com/djrausch/billtracker/models/Bill.java
15. REALM - A MOBILE DATABASE REPLACEMENT
FIELD TYPES
▸Supports standard field types including Date
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 actually) within Realm. Moreover, subclasses of
RealmObject and RealmList<? extends RealmObject> are supported to model
relationships.
The boxed types Boolean, Byte, Short, Integer, Long, Float and Double can also
be used in model classes. Using these types, it is possible to set the value of a
field to null.
https://realm.io/docs/java/latest/#field-types
17. REALM - A MOBILE DATABASE REPLACEMENT
QUERIES
▸You can group conditions for complex queries
RealmResults<User> r = realm.where(User.class)
.greaterThan("age", 10) //implicit AND
.beginGroup()
.equalTo("name", "Peter")
.or()
.contains("name", "Jo")
.endGroup()
.findAll();
https://realm.io/docs/java/latest/#logical-operators
18. REALM - A MOBILE DATABASE REPLACEMENT
CREATING MODEL
realm.beginTransaction();
User user = realm.createObject(User.class);
user.setName("John");
user.setEmail("john@corporation.com");
realm.commitTransaction();
https://realm.io/docs/java/latest/#creating-objects
19. REALM - A MOBILE DATABASE REPLACEMENT
CREATING MODEL
final Bill b = new Bill(name.getText().toString(), "", repeatingItem.code,
selectedDueDate.toDate(), payUrl.getText().toString(), (int) (amount.getValue() *
100));
realm.executeTransaction(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
realm.copyToRealm(b);
}
});
https://github.com/djrausch/BillTracker/blob/master/app/src/main/java/com/djrausch/billtracker/AddOrEditBillActivity.jav
a#L171
20. REALM - A MOBILE DATABASE REPLACEMENT
READING MODEL
BillTrackerApplication.getRealm().where(Bill.class).contains("
uuid", billUuid).findFirst()
‣ findFirst()
‣ findAll()
‣ findAllSorted()
‣ These all have an async version as well
https://github.com/djrausch/BillTracker/blob/master/app/src/main/java/com/djrausch/billtracker/AddOrEditBill
Activity.java#L109
21. REALM - A MOBILE DATABASE REPLACEMENT
UPDATING MODEL
realm.executeTransaction(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
editBill.setName(name.getText().toString());
editBill.setRepeatingType(repeatingItem.code);
editBill.setDueDate(selectedDueDate.toDate());
editBill.setPayUrl(payUrl.getText().toString());
editBill.setAmountDue((int) (amount.getValue() * 100));
}
});
https://github.com/djrausch/BillTracker/blob/master/app/src/main/java/com/djrausch/billtracker/AddOrEditBill
Activity.java#L155
22. REALM - A MOBILE DATABASE REPLACEMENT
DELETING MODEL
getRealm().executeTransaction(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
bill.deleteFromRealm();
}
});
https://github.com/djrausch/BillTracker/blob/master/app/src/main/java/com/djrausch/billtracker/AddOrEditBill
Activity.java#L218
23. REALM - A MOBILE DATABASE REPLACEMENT
RELATIONSHIPS
▸Many-to-One
▸Used for One-to-One
▸Many-to-Many
https://realm.io/docs/java/latest/#relationships
24. REALM - A MOBILE DATABASE REPLACEMENT
MANY-TO-ONE
public class Contact extends RealmObject {
private Email email;
// Other fields…
}
https://realm.io/docs/java/latest/#many-to-one
25. REALM - A MOBILE DATABASE REPLACEMENT
MANY-TO-MANY
public class Bill extends RealmObject {
…
public RealmList<BillPaid> paidDates;
…
}
final BillPaid billPaid = new BillPaid(new Date());
BillTrackerApplication.getRealm().executeTransaction(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
bill.setDueDate(DateUtil.createNextDueDate(bill));
bill.getPaidDates().add(billPaid);
}
});
https://github.com/djrausch/BillTracker/blob/master/app/src/main/java/com/djrausch/billtracker/models/Bill.java#L28
https://github.com/djrausch/BillTracker/blob/master/app/src/main/java/com/djrausch/billtracker/util/BillUtil.java#L20
https://realm.io/docs/java/latest/#many-to-many
26. REALM - A MOBILE DATABASE REPLACEMENT
THREADING
The only rule to using Realm across threads is to remember that
Realm, RealmObject or RealmResults instances cannot be passed
across threads.
Get Realm in any thread you need it.
getRealm().where(Bill.class).equalTo("deleted",
false).findAllSortedAsync("dueDate");
https://github.com/djrausch/BillTracker/blob/master/app/src/main/java/com/djrausch/billtracker/util/BillUtil.java#L43
27. REALM - A MOBILE DATABASE REPLACEMENT
USING WITH RETROFIT
It just works!
apiService.getUserBills(BillTrackerApplication.getUserToken()).enqueue(new Callback<List<Bill>>() {
@Override
public void onResponse(Call<List<Bill>> call, final Response<List<Bill>> response) {
for (Bill b : response.body()) {
Log.d("Bill", b.toString());
}
BillTrackerApplication.getRealm().executeTransaction(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
realm.copyToRealmOrUpdate(response.body());
}
});
}
});
https://github.com/djrausch/BillTracker/blob/master/app/src/main/java/com/djrausch/billtracker/network/controller
s/BillApi.java#L45
28. REALM - A MOBILE DATABASE REPLACEMENT
ADAPTERS
‣ RealmRecyclerViewAdapter
‣ Keeps the data updated from a RealmResult or RealmList
‣ No need to notifyDataSetChanged()
https://github.com/djrausch/BillTracker/blob/master/app/src/main/java/com/djrausch/billtracker/adapters/M
ainRecyclerViewAdapter.java
https://realm.io/docs/java/latest/#adapters
29. REALM - A MOBILE DATABASE REPLACEMENT
LIMITATIONS
▸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.
▸The length of field names has a upper limit of 63 character.
▸Nested transactions are not supported, and an exception is thrown if
they are detected.
▸Strings and byte arrays (byte[]) cannot be larger than 16 MB.
▸Does not support lists of primitive types (String, Ints, etc), yet.
https://realm.io/docs/java/latest/#current-limitations
30. REALM - A MOBILE DATABASE REPLACEMENT
QUESTIONS?
▸Use #phxmobi as the twitter hashtag and follow
@phxmobifestival for updates.
▸Download Phoenix Mobile Festival App (search for 'phxmobi')
from AppStore or Google Play. From the app you can create your
own agenda for the day and provide feedback on the sessions.
▸Slides will be on djraus.ch/realm soon!
▸Bill Tracker is open source -
https://github.com/djrausch/BillTracker
Hinweis der Redaktion
Migrations work much like onUpgrade in Sqlite
boxed types
I haven’t used this yet.
Android KeyStore
Note, I am not using the new RealmResults. It is recommended to only use this to notify the UI of any data changes.
I am still new with RxJava so this isn’t that advanced. Realm docs go into more details on this
POJO
Can have public, private, protected methods as well
contains is like where clause in sql
If using this method, and want to perform action on the bill, you must use the object returned by copyToRealm
Append async to method
Update the model as you would any object. Do it inside a transaction (should probably use Async transaction)
Setting the value to null for a RealmList field will clear the list. That is, the list will be empty (length zero), but no objects have been deleted. The getter for a RealmList will never return null. The returned object is always a list but the length might be zero.
The realm instance cannot be shared between threads. Just get the instance again, and data in the other thread will be updated due to the auto updates