The Model

We need some in-memory representation of a to-do item. That comes in the form of a ToDoModel POJO class.

In addition to a unique ID, there are four pieces of additional data that we track about each to-do item in ToDoModel:

We could track more information — last-updated timestamp, revision history, categories, etc. — but we are trying to keep this relatively simple.

ToDoModel, like the actions, uses AutoValue for immutability. So, our class has the @AutoValue annotation and abstract methods for each of the properties that we are tracking:

@AutoValue
public abstract class ToDoModel {
  public abstract String id();
  public abstract boolean isCompleted();
  public abstract String description();
  @Nullable public abstract String notes();
  public abstract Calendar createdOn();

The notes() method is annotated with @Nullable, so AutoValue will allow null for that property. All other properties are required.

We are using the builder pattern, so we have an @AutoValue.Builder-annotated static class named Builder, with corresponding setter methods for the properties, plus build() to create a ToDoModel instance from the Builder:

  @AutoValue.Builder
  public abstract static class Builder {
    abstract Builder id(String id);
    public abstract Builder isCompleted(boolean isCompleted);
    public abstract Builder description(String desc);
    public abstract Builder notes(String notes);
    abstract Builder createdOn(Calendar date);
    public abstract ToDoModel build();
  }

We also have three methods for getting Builder instances:

  static Builder builder() {
    return(new AutoValue_ToDoModel.Builder());
  }

  public static Builder creator() {
    return(builder()
      .isCompleted(false)
      .id(UUID.randomUUID().toString())
      .createdOn(Calendar.getInstance()));
  }

  public Builder toBuilder() {
    return(builder()
      .id(id())
      .isCompleted(isCompleted())
      .description(description())
      .notes(notes())
      .createdOn(createdOn()));
  }

So, creating a new ToDoModel instance is a matter of calling creator(), then whatever setters are necessary, then build() to create the instance. To modify an existing ToDoModel, call toBuilder() on it, then whatever setters are necessary, then build() to create the modified instance.

While the sample app uses Room to save the to-do items, ToDoModel is not a Room @Entity. There is a separate ToDoEntity class that models our database table, and the app maps between ToDoModel and ToDoEntity instances as needed.


Prev Table of Contents Next

This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.