Use CoGo to build a to-do list in Kotlin

Introduction

In this tutorial, you’ll use Code on the Go (CoGo™) to write, build, and test an Android app with Kotlin and Jetpack Compose. This includes the following:

  • A specification for the app
  • Step-by-step instructions for building the app in CoGo
  • An explanation of how the code works

Specifically, you’ll build a to-do list app that lets you add tasks, view your list, and mark items as complete. Your tasks are saved automatically, so they will still be there when you close and reopen the app.

Jetpack Compose is a more advanced approach to building Android apps. If you are new to programming, some of the concepts may be unfamiliar. That is fine. The complete code is provided for you to copy and paste, and each part is explained after you add it. To help you along, we’ve also published a video version of this tutorial:

Parts of the app

The finished app features the following:

  • Add a task: The user types a task description into a text field and taps the Add button to add it to the list.
  • View tasks: All added tasks are displayed in a scrollable list below the input area.
  • Mark as complete: The user taps a checkbox next to a task to mark it as complete. Completed tasks are displayed with a strikethrough.
  • Persistence: Tasks are saved automatically. When the user closes and reopens the app, all tasks and their completion status are preserved.

When you install it, the app will look like the image below.

What is Jetpack Compose?

Before you create the project, it is helpful to have some knowledge of Jetpack Compose.

In traditional Android development, the user interface is defined in XML layout files. These files are separate from the Kotlin or Java code that controls the app’s behavior. Jetpack Compose takes a different approach. The interface is defined directly in Kotlin code, using functions called composables. The interface and the logic are written in the same place, which makes the code easier to read and maintain.

Compose is the recommended modern approach for building Android user interfaces, and CoGo supports it fully. In this tutorial, you will write your entire user interface in Kotlin, with no XML layout files.

Start the project

When you open CoGo, the main menu is displayed.

  1. On the main menu, tap Create a new project. The New project page is displayed. It contains templates with starter code for different kinds of projects.
  2. Tap the Empty Compose Activity template. A configuration page for the project is displayed. (The Empty Compose Activity template sets up your project with Jetpack Compose already configured, which saves you several manual setup steps.)
  3. In the App name field, enter ToDoApp. To use this tutorial’s sample code, you must enter the name exactly as shown here.
  4. In the Project language menu, select Kotlin.
  5. In the Minimum SDK menu, leave the default option selected.
  6. In the lower-right corner, tap the Create a new project button. CoGo will initialize the project.

What happens during initialization?

As part of project initialization, CoGo creates files and directories for the template you selected. During initialization, the top of the page displays a moving progress bar, while the bottom of the page displays status messages. For detailed information about the initialization tasks, swipe up from the bottom to display the output panel. Swipe down to hide the panel when you are done viewing it.

When the project has fully initialized, the “Project initialized” message is displayed at the bottom of the page. The Build icon (a green triangle) is displayed at the top of the page near the project’s name.

Open the source file

CoGo provides a file browser to navigate the contents of your project. To use the file browser:

  1. Tap the Project menu, which is represented by the hamburger icon in the top left corner.
  2. Tap any of the folder icons to see the contents.

In this tutorial, you only modify one file:

MainActivity.kt

This is the source file for the main activity of the app. It is where you will write all of your Kotlin and Compose code. To open MainActivity.kt, begin with the main project folder and open the following folders in order:

app → src → main → java → com → example → todoapp

The todoapp folder contains the file MainActivity.kt. Tap MainActivity.kt to open it in the code editor. The file contains default Compose starter code generated by the template. In the next step, you will replace this code with the code for this tutorial.

Add the tutorial code to MainActivity.kt

Select all of the existing content in MainActivity.kt and delete it. Then paste in the following code (for your convenience, simply tap the “Copy” button just below):
package com.example.todoapp

import android.content.Context
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.unit.dp
import androidx.compose.material3.ExperimentalMaterial3Api
import com.example.todoapp.ui.theme.MyComposeApplicationTheme
import org.json.JSONArray
import org.json.JSONObject

data class Task(
    val id: Long = System.currentTimeMillis(),
    var text: String,
    var isCompleted: Boolean = false
)

class MainActivity : ComponentActivity() {

    private fun saveTasks(tasks: List<Task>) {
        val prefs = getSharedPreferences("todo_prefs", Context.MODE_PRIVATE)
        val jsonArray = JSONArray()
        for (task in tasks) {
            val obj = JSONObject()
            obj.put("id", task.id)
            obj.put("text", task.text)
            obj.put("isCompleted", task.isCompleted)
            jsonArray.put(obj)
        }
        prefs.edit().putString("tasks", jsonArray.toString()).apply()
    }

    private fun loadTasks(): MutableList<Task> {
        val prefs = getSharedPreferences("todo_prefs", Context.MODE_PRIVATE)
        val json = prefs.getString("tasks", "[]") ?: "[]"
        val jsonArray = JSONArray(json)
        val tasks = mutableListOf<Task>()
        for (i in 0 until jsonArray.length()) {
            val obj = jsonArray.getJSONObject(i)
            tasks.add(
                Task(
                    id = obj.getLong("id"),
                    text = obj.getString("text"),
                    isCompleted = obj.getBoolean("isCompleted")
                )
            )
        }
        return tasks
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            val tasks = remember { mutableStateListOf<Task>().also { it.addAll(loadTasks()) } }
            var newTaskText by remember { mutableStateOf("") }

            MyComposeApplicationTheme {
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colorScheme.background
                ) {
                    ToDoScreen(
                        tasks = tasks,
                        newTaskText = newTaskText,
                        onTextChange = { newTaskText = it },
                        onAddTask = {
                            if (newTaskText.isNotBlank()) {
                                tasks.add(Task(text = newTaskText.trim()))
                                saveTasks(tasks)
                                newTaskText = ""
                            }
                        },
                        onToggleComplete = { task ->
                            val index = tasks.indexOf(task)
                            if (index != -1) {
                                tasks[index] = task.copy(isCompleted = !task.isCompleted)
                                saveTasks(tasks)
                            }
                        }
                    )
                }
            }
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ToDoScreen(
    tasks: List<Task>,
    newTaskText: String,
    onTextChange: (String) -> Unit,
    onAddTask: () -> Unit,
    onToggleComplete: (Task) -> Unit
) {
    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(16.dp)
    ) {
        Text(
            text = "My To-Do List",
            style = MaterialTheme.typography.headlineMedium,
            modifier = Modifier.padding(bottom = 16.dp)
        )

        Row(
            modifier = Modifier.fillMaxWidth(),
            verticalAlignment = Alignment.CenterVertically
        ) {
            TextField(
                value = newTaskText,
                onValueChange = onTextChange,
                placeholder = { Text("Enter a task...") },
                modifier = Modifier.weight(1f)
            )
            Spacer(modifier = Modifier.width(8.dp))
            Button(onClick = onAddTask) {
                Text("Add")
            }
        }

        Spacer(modifier = Modifier.height(16.dp))

        LazyColumn {
            items(tasks.size) { index ->
                val task = tasks[index]
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(vertical = 4.dp),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Checkbox(
                        checked = task.isCompleted,
                        onCheckedChange = { onToggleComplete(task) }
                    )
                    Text(
                        text = task.text,
                        style = if (task.isCompleted)
                            MaterialTheme.typography.bodyLarge.copy(
                                textDecoration = TextDecoration.LineThrough
                            )
                        else
                            MaterialTheme.typography.bodyLarge,
                        modifier = Modifier.padding(start = 8.dp)
                    )
                }
            }
        }
    }
}
Note: The package name on the first line of the file (com.example.todoapp) and in the theme import must match your project’s package name. CoGo creates the package name from the app name you entered during project setup, which is why the name ToDoApp must be entered exactly as shown. The theme is named MyComposeApplicationTheme because that is the name the Compose template gives it. It does not change with your app name. If you open ui/theme/Theme.kt in your project, you will see this name.

Understand the code

Now that the code is in place, this section explains how it works. The app has four main parts.

Part 1: The task data class

A data class in Kotlin is a concise way to represent a piece of information. The app uses a data class called Task to represent a single to-do item. Each task has three properties:

  • id: A unique identifier, generated automatically from the current time.
  • text: The text description of the task.
  • isCompleted: A boolean value that tracks whether the task has been marked as complete. It starts as false.
data class Task(
    val id: Long = System.currentTimeMillis(),
    var text: String,
    var isCompleted: Boolean = false
)

Part 2: Saving and loading tasks

The app saves tasks using SharedPreferences, which is Android’s built-in system for storing small amounts of data. Tasks are converted to JSON format for storage and converted back when the app loads. Two functions handle this:

  • saveTasks() converts the task list to a JSON string and stores it.
  • loadTasks() reads the stored JSON string and converts it back into a list of tasks.

Together, these two functions ensure that tasks are preserved between sessions.

Part 3: The main activity and state

The MainActivity class is the entry point of the app. Its onCreate method sets up the Compose interface and manages state, which is data that can change over time. When state changes, Compose automatically updates the interface.

val tasks = remember { mutableStateListOf().also { it.addAll(loadTasks()) } }
var newTaskText by remember { mutableStateOf("") }

  • mutableStateListOf holds the list of tasks. The interface updates whenever a task is added or changed.
  • mutableStateOf holds the text the user is currently typing.

The same method defines two actions:

  • onAddTask adds a new task to the list, saves the list, and clears the text field.
  • onToggleComplete finds a task in the list, reverses its completion status, and saves the list.

Part 4: The user interface

The ToDoScreen composable describes the entire interface:

  • A title at the top of the screen.
  • A Row containing a text field and an Add button.
  • A LazyColumn, which is Compose’s efficient scrollable list. It displays all of the tasks.
  • Within each task row, a Checkbox and a Text label. When a task is complete, its text is displayed with a strikethrough.

What does @OptIn do?

The line @OptIn(ExperimentalMaterial3Api::class) above ToDoScreen tells Kotlin that you are aware that some of the Material components used in this function are marked as experimental. Without it, the build stops with an error about an experimental API.

Build the app

When you have entered all of the code, tap the green Build icon in the action bar. When the build finishes, tap to install the app.

After the app is installed and launched, you can test it:

  1. Type a task description in the text field and tap Add. The task appears in the list.
  2. Add a few more tasks.
  3. Tap the checkbox next to a task to mark it as complete. The task text is displayed with a strikethrough.
  4. Close the app completely and reopen it. Your tasks are still there, exactly as you left them.

If the build fails

Swipe up from the bottom of the project screen to display the output panel. Then, use the Build Output tab to look for lines that begin with the letter “e.” These lines name the file and line number of each error. The most common cause is a typo or a missing line when pasting the code, so compare your file with the code on this page.

Congratulations!

Using CoGo, you built a complete, fully usable to-do app with Kotlin and Jetpack Compose.

From here, you could extend the app with additional features, such as:

  • Task deletion: Allow the user to remove tasks from the list.
  • Due dates: Add a date field to each task.
  • Categories or priorities: Organize tasks into groups.
  • Room database: For apps with larger amounts of data, Room is Android’s recommended solution for more robust persistence.