Last active
September 8, 2016 05:40
-
-
Save esafirm/c58dccb672a8b932f3bb49e0a1be0cc5 to your computer and use it in GitHub Desktop.
Realm object repository sample
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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