Skip to content

Instantly share code, notes, and snippets.

@esafirm
Last active September 8, 2016 05:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save esafirm/c58dccb672a8b932f3bb49e0a1be0cc5 to your computer and use it in GitHub Desktop.
Save esafirm/c58dccb672a8b932f3bb49e0a1be0cc5 to your computer and use it in GitHub Desktop.
Realm object repository sample
// The code using Java 8 Lambda
public class NoteRepository {
public static Note createNote() {
Note note = new Note();
note.setId(new RandomString(6).nextString());
return note;
}
public static void updateTitle(String noteId, String title) {
Note note = findNote(noteId);
if (note != null) {
getRealm().executeTransaction(realm -> note.setTitle(title));
}
}
public static Note findNote(String noteId) {
return query().equalTo(Note.Column.ID, noteId).findFirst();
}
public static RealmResults<Note> search(String queryString) {
return query().contains(Note.Column.TITLE, queryString)
.or()
.contains(Note.Column.TAGS, queryString)
.findAllSorted(Note.Column.CATEGORY);
}
public static void deleteNote(String noteId) {
Note note = findNote(noteId);
if (note != null) {
getRealm().executeTransaction(realm -> note.deleteFromRealm());
}
}
// can be moved to Realm utility class, ex: RealmHelper.java
private static RealmQuery<Note> query() {
return getRealm().where(Note.class);
}
// can be moved to Realm utility class, or injected using DI
private static Realm getRealm() {
return Realm.getDefaultInstance();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment