Tutorial: Demo Project

Walk-through of an example Android note taking app using ObjectBox.

What is ObjectBox? It’s a standalone database that makes object persistence simple and super fast.

This tutorial will walk you through a simple note-taking app explaining how to do basic operations with ObjectBox. To just integrate ObjectBox into your project, look at the Getting Started page.

You can check out the example code from GitHub. This allows you to run the code and explore it in its entirety. It is a simple Android app for taking notes where you can add new notes by typing in some text and delete notes by clicking on an existing note.

Java
Kotlin
Dart
Java
git clone https://github.com/objectbox/objectbox-examples.git
cd objectbox-examples/android-app
Kotlin
git clone https://github.com/objectbox/objectbox-examples.git
cd objectbox-examples/android-app-kotlin
Dart
git clone https://github.com/objectbox/objectbox-dart.git
cd objectbox-dart/objectbox/examples/flutter/objectbox_demo

The Note entity and Box class

To begin let’s jump right into the code: among the sources the entity class:Note. It is persisted (saved) in the database and contains all data that is part of a note, like an id, note text and the creation date.

Java
Kotlin
Dart
Java
src/Note.java
@Entity
public class Note {
@Id
long id;
String text;
String comment;
Date date;
...
}
Kotlin
src/Note.kt
@Entity
data class Note(
@Id var id: Long = 0,
var text: String? = null,
var comment: String? = null,
var date: Date? = null
)
Dart
lib/main.dart
()
class Note {
int id;
String text;
String? comment;
DateTime date;
...
}

In general, an ObjectBox entity is an annotated class persisted in the database with its properties. In order to extend our note or to create new entities, you simply modify or create new plain classes and annotate them with @Entity and @Id.

Java
Kotlin
Dart
Java

Go ahead and build the project, for example by using Build > Make project in Android Studio. This triggers ObjectBox to generate some classes, like MyObjectBox.java, and some other classes used by ObjectBox internally.

Kotlin

Go ahead and build the project, for example by using Build > Make project in Android Studio. This triggers ObjectBox to generate some classes, like MyObjectBox.kt, and some other classes used by ObjectBox internally.

Dart

To generate ObjectBox binding code for your entities, make sure to run pub run build_runner build after making any changes to the entity classes. ObjectBox generator will look for all @Entity annotations in your lib folder and create a single database definition lib/objectbox-model.json and supporting code in lib/objectbox.g.dart.

You should commit objectbox-model.json into your source control (e.g. git) and add objectbox.g.dart to the ignore list (e.g. .gitignore), otherwise, the build_runner will complain about it being changed each time you pull a change.

The generator will process lib and test folders separately and create a separate database in each if it finds annotated entities there. This is useful if you need a separate test database. If you're just writing tests for your own code, you won't have any annotations in the test folder so no DB model will be created there.

Inserting notes

To see how new notes are added to the database, take a look at the following code fragments. The Box<Note> provides database operations for Note objects.

Java
Kotlin
Dart
Java
NoteActivity.java
@Override
public void onCreate(Bundle savedInstanceState) {
...
notesBox = ObjectBox.get().boxFor(Note.class);
...
}

Note: In the example project, ObjectBox is the name of a helper class to set up and keep a reference to BoxStore.

Kotlin
NoteActivity.kt
public override fun onCreate(savedInstanceState: Bundle?) {
...
notesBox = ObjectBox.boxStore.boxFor()
...
}

Note: In the example project, ObjectBox is the name of a helper class to set up and keep a reference to BoxStore.

Dart
lib/main.dart
class ViewModel {
final Store _store;
late final Box<Note> _box;
ViewModel(Directory dir)
: _store = Store(getObjectBoxModel(), directory: dir.path + '/objectbox') {
_box = _store.box<Note>();
}
...

When a user clicks the ADD button the method addNote() is called. There, a new Note object is created and put into the database using the Box reference:

Java
Kotlin
Dart
Java
NoteActivity.java
private void addNote() {
...
Note note = new Note();
note.setText(noteText);
note.setComment(comment);
note.setDate(new Date());
notesBox.put(note);
Log.d(App.TAG, "Inserted new note, ID: " + note.getId());
...
}
Kotlin
NoteActivity.kt
private fun addNote() {
...
val note = Note(text = noteText, comment = comment, date = Date())
notesBox.put(note)
Log.d(App.TAG, "Inserted new note, ID: " + note.id)
...
}
Dart
void addNote() {
_box.put(Note(_noteInputController.text));
}

Note that the ID property (0 when creating the Note object), is assigned by ObjectBox during put().

Removing/deleting notes

When the user taps a note, it is deleted. The Box provides remove() to achieve this:

Java
Kotlin
Dart
Java
NoteActivity.java
OnItemClickListener noteClickListener = new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Note note = notesAdapter.getItem(position);
notesBox.remove(note);
Log.d(App.TAG, "Deleted note, ID: " + note.getId());
...
}
};
Kotlin
NoteActivity.kt
private val noteClickListener = OnItemClickListener { _, _, position, _ ->
notesAdapter.getItem(position)?.also {
notesBox.remove(it)
Log.d(App.TAG, "Deleted note, ID: " + it.id)
}
...
}
Dart
...
onTap: () => _vm._box.remove(notes[index].id),
...

Querying notes

To query and display notes with a list adapter a Query instance is built once:

Java
Kotlin
Dart
Java
NoteActivity.java
@Override
public void onCreate(Bundle savedInstanceState) {
...
// Query all notes, sorted a-z by their text.
notesQuery = notesBox.query().order(Note_.text).build();
...
}
Kotlin
NoteActivity.kt
public override fun onCreate(savedInstanceState: Bundle?) {
...
// Query all notes, sorted a-z by their text.
notesQuery = notesBox.query {
order(Note_.text)
}
...
}
Dart
class ViewModel {
final Store _store;
late final Box<Note> _box;
late final Query<Note> _query;
ViewModel(Directory dir)
: _store = Store(getObjectBoxModel(), directory: dir.path + '/objectbox') {
_box = _store.box<Note>();
_query = _box.query().order(Note_.date, flags: Order.descending).build();
}
...

And then executed each time any notes change:

Java
Kotlin
Dart
Java
NoteActivity.java
private void updateNotes() {
List<Note> notes = notesQuery.find();
notesAdapter.setNotes(notes);
}
Kotlin
NoteActivity.kt
private fun updateNotes() {
val notes = notesQuery.find()
notesAdapter.setNotes(notes)
}
Dart
List<Note> get allNotes => _query.find();

In addition to an order, you can add various conditions, like equality or less/greater than, when building a query.

Updating notes and more

What is not shown in the example, is how to update an existing (== the ID is not 0) note. Just modify any of its properties and call put() again with the changed object:

Java
Kotlin
Dart
Java
note.setText("This note has changed.");
notesBox.put(note);
Kotlin
note.text = "This note has changed."
notesBox.put(note)
Dart
note.text = "This note has changed.";
_box.put(note);

There are additional methods to put, find, query, count or remove entities. Check out the methods of the Box class in API docs (for Java/Kotlin or Dart) to learn more.

Setting up the database

Now that you saw ObjectBox in action, how did we get that BoxStore instance? Typically you should set up a BoxStore once for the whole app. This example uses a helper class as recommended in the Getting Started guide.

Remember: ObjectBox is a NoSQL database on its own and thus NOT based on SQL or SQLite. That’s why you do not need to set up “CREATE TABLE” statements during initialization.

Note: it is perfectly fine to never close the database. That’s even recommended for most apps.