If you’ve been following along with parts 1-3, you now have an (almost) working todo list application. The only thing we are missing is persisting the data. Running your Android app now and rotating your screen will show you that the items you add won’t persist, and disappear anytime an activity is killed and recreated. This post will show you how to write the list to a text file and read from it.

Following up on part 2 which demonstrates how to create your Android app and configure Kotlin, we’ll begin building the heart and soul of a Todo List application - the list!

Data Model

Let’s begin by defining our model. We’re going to create a simple class that has two fields, one for description and one for whether or not it’s completed. Here is how this class will look in Kotlin:

	data class Task(var description: String, var completed: Boolean = false) : Serializable

You may not believe it, but that’s all we need. Let’s talk about what’s happening here:

  • A data class is a special class in Kotlin that provides you with default behaviors for all your Object methods like toString() hashCode() equals() and copy(). Read more here.
  • Kotlin allows for default constructors to be defined right with the class name.
  • Kotlin allows for default parameters. So in this case, we have a constructor that can be used as Task("Description") and it will default to incomplete, or we can call it with Task("Description", true) to set the initial value of the completed boolean.
  • We’ve had our class implement Serializable. In this simple app, we’re just going to save the data to a text file instead of over complicating it with SQLite.

This blog post is going to discuss creating a project from scratch in Kotlin. We will build a sample Todo List application that will not be very complicated, but covers enough to show the benefits of Kotlin. Part 1 will discuss creating a new project and configuring Kotlin. If you’re familiar with that, copy the MainActivity.kt code and skip to part 2 to begin building the app.

This tutorial assumes a basic knowledge of programming, and some familiarity with Android. If you have any questions please leave them in the comments, and I will udpate these posts with a deeper explanation.

It is tough enough maintaing your app by updating the support library version numbers every time a new version is out, let alone factoring in any other third party libraries you may use. This is especially painful if you have multiple modules, as you have to update the version in each build.gradle file. Thankfully, we can make use of the project level gradle file to make this more maintainable.