A simple ToDo app to demonstrate the use of Realm Database in android
Creating a Realm Model Class
@RealmClass
open class Note() : RealmModel {
@PrimaryKey
var id: String = ""
@Required
var title: String? = ""
@Required
var description: String? = ""
}
Adding Data Into Realm
val note = r.createObject(Note::class.java, UUID.randomUUID().toString())
note.title = noteTitle
note.description = noteDescription
note.title = noteTitle
note.description = noteDescription
realm.insertOrUpdate(note)
}
}
“>
fun addNote(noteTitle: String, noteDescription: String) { realm.executeTransaction { r: Realm -> val note = r.createObject(Note::class.java, UUID.randomUUID().toString()) note.title = noteTitle note.description = noteDescription realm.insertOrUpdate(note) } }
Query data from the Realm database
<div class="highlight highlight-source-kotlin position-relative" data-snippet-clipboard-copy-content="private fun getAllNotes(): MutableLiveData<List> {
val list = MutableLiveData<List>()
val notes = realm.where(Note::class.java).findAll()
list.value = notes?.subList(0, notes.size)
return list
}
“>
private fun getAllNotes(): MutableLiveData<List<Note>> { val list = MutableLiveData<List<Note>>() val notes = realm.where(Note::class.java).findAll() list.value = notes?.subList(0, notes.size) return list }
Updating data
fun updateNote(id: String, noteTitle: String, noteDesc: String) {
val target = realm.where(Note::class.java)
.equalTo("id", id)
.findFirst()
realm.executeTransaction {
target?.title = noteTitle
target?.description = noteDesc
realm.insertOrUpdate(target)
}
}
Deleting A Single data of a paricular Realm object
fun deleteNote(id: String) {
val notes = realm.where(Note::class.java)
.equalTo("id", id)
.findFirst()
realm.executeTransaction {
notes!!.deleteFromRealm()
}
}
Deleting all data from a Realm object
r.delete(Note::class.java)
}
}
“>
}
}
“>
fun deleteAllNotes() { realm.executeTransaction { r: Realm -> r.delete(Note::class.java) } }