How Do I Use Kotlin to Model Tasks in an Android App?

In article 1, you created Task Notes and its empty screen. Now you will describe the data behind a task using Kotlin. You will create a Task model, prepare sample tasks, and display one task on the existing screen. The next article will turn those samples into a scrolling list.

Practical goal

By the end, you will be able to declare typed properties, use default and named arguments, create a read-only list, and produce an updated task with copy().

Continue with the same Android Studio project. This example keeps the package org.kodejava.tasknotes, the generated TaskNotesTheme, and minimum SDK API 24 from article 1. If you used your own package, adjust the package declarations and imports below.

1. Create the Task model

Create the model package below org.kodejava.tasknotes. Add this file:

File: app/src/main/java/org/kodejava/tasknotes/model/Task.kt

package org.kodejava.tasknotes.model

data class Task(
    val id: Long,
    val title: String,
    val isCompleted: Boolean = false
)

A model describes information that the app works with. Here, each task has three properties:

Property Type Purpose
id Long Identifies the task even when its title changes
title String Holds the text shown to the user
isCompleted Boolean Records whether the task is done

The colon introduces a type. Boolean has two values: true and false. The default value means a new task starts incomplete unless you supply another value.

String does not accept null. It still accepts empty text such as ""; non-null types do not replace input validation. You will add form validation in a later article.

The data keyword asks Kotlin to generate useful operations such as equality checks, readable text output, and copying. Keep the properties in the primary constructor so those generated operations include them. See the official data class documentation.

2. Understand val and named arguments

This is an example of constructing a task; you do not need to add it to a file yet:

val task = Task(id = 1L, title = "Learn Kotlin basics")

val declares a reference that cannot be reassigned. The model also uses val properties, so you cannot assign a new title directly to an existing task.

1L is a Long literal. Named arguments such as title = ... make constructor calls easier to read. Since we omitted isCompleted, its value is false.

Kotlin also has var for variables that can be reassigned. We use val here to make changes explicit through new objects.

3. Prepare reusable sample data

Create a data package and add the following file:

File: app/src/main/java/org/kodejava/tasknotes/data/SampleTasks.kt

package org.kodejava.tasknotes.data

import org.kodejava.tasknotes.model.Task

fun sampleTasks(): List<Task> = listOf(
    Task(id = 1L, title = "Learn Kotlin basics"),
    Task(id = 2L, title = "Create the Task model", isCompleted = true),
    Task(id = 3L, title = "Build the task list")
)

fun declares a function. This function takes no arguments and returns a List<Task>, meaning a list whose elements are tasks. The = introduces a function with a single expression as its body.

listOf() creates the sample list. List exposes read-only operations: callers can inspect its elements but cannot call add() through that interface. A read-only interface is not a general guarantee that an underlying collection can never change. Our sample contains tasks with read-only properties and exposes no mutation operations.

The sample IDs are distinct and remain the same each time this function is called. They are manually assigned tutorial values; the function does not generate IDs for future user-created tasks. A title is not an ID because two tasks may have the same title.

Reference: Kotlin collections overview.

4. Display a task on the existing screen

In MainActivity.kt, add this import alongside the existing imports:

import org.kodejava.tasknotes.data.sampleTasks

Replace only the existing TaskNotesScreen() function with the code below. Keep MainActivity, its Scaffold and innerPadding, all existing Compose imports, and TaskNotesScreenPreview() from article 1.

File: app/src/main/java/org/kodejava/tasknotes/MainActivity.kt

@Composable
private fun TaskNotesScreen(modifier: Modifier = Modifier) {
    val tasks = sampleTasks()
    val task = tasks.first()
    val status = if (task.isCompleted) "Completed" else "Not completed"

    Column(
        modifier = modifier.fillMaxSize().padding(24.dp),
        verticalArrangement = Arrangement.spacedBy(8.dp)
    ) {
        Text(
            text = "Task Notes",
            style = MaterialTheme.typography.headlineMedium
        )
        Text(
            text = task.title,
            style = MaterialTheme.typography.bodyLarge
        )
        Text(text = "Status: $status")
        Text(text = "Sample tasks: ${tasks.size}")
    }
}

Kotlin infers the types of tasks, task, and status from their values. first() reads the first element. It is safe here because our sample function always returns three tasks; it would throw an exception for an empty list.

An if expression produces the status text. String templates insert values into text: $status inserts a variable, while ${tasks.size} evaluates an expression.

This screen only reads fixed sample data. Calling sampleTasks() during composition is acceptable for this tiny example; it is not a strategy for loading database data. Interactive state and its ownership come later in the series.

5. Create an updated task with copy()

To try a completed version, replace this line inside TaskNotesScreen():

val task = tasks.first()

with:

val original = tasks.first()
val task = original.copy(isCompleted = true)

The copied task keeps the original ID and title but has a new completion value. The original task and the task stored in the sample list remain incomplete. Copying an object does not replace an element in a list.

copy() is shallow: nested objects would still be shared. This model contains only a number, text, and a Boolean, so no mutable nested collection is involved.

After checking the result, restore val task = tasks.first() so your project matches the starting point for article 3.

6. Verify the result

  1. Sync the project if Android Studio requests it, then run the app on the emulator or phone used in article 1.
  2. Check that the screen shows the following text:
Task Notes
Learn Kotlin basics
Status: Not completed
Sample tasks: 3
  1. Refresh the existing Compose preview. It should show the same sample content.
  2. Try the copy() change from step 5. The status should become Completed, with the same title and sample count.
  3. Restore the original line and run again.

If Task or sampleTasks is unresolved, check the file package declarations and imports. If the compiler reports a type mismatch for an ID, use a Long literal such as 1L. If the preview cannot load, resolve build errors before refreshing it.

These are verification steps for your project. This draft’s Android build and device behavior have not been executed in an Android SDK environment.

Practice

  • Add a fourth sample task with ID 4L. Verify that the count becomes 4.
  • Display tasks[1] instead of the first task. The second task should show Completed. List indexes start at zero.
  • Use copy(title = "Review Kotlin basics") on the first task and observe that the original sample title stays unchanged.

Restore the three original samples and tasks.first() before continuing to the next article.

Gradle dependencies and compatibility

No additional Gradle dependencies are required. The model and sample function use the Kotlin standard library supplied by the existing Kotlin Android project. The screen reuses the Compose dependencies configured in article 1.

Keep the existing plugin and dependency versions in build.gradle.kts, app/build.gradle.kts, and gradle/libs.versions.toml if present. This lesson introduces no version-specific library API and does not require a Kotlin, Android Gradle Plugin, or Compose upgrade. Official Compose setup guidance remains the reference for project configuration.

Next in the series

In article 3, How Do I Display Tasks in a LazyColumn with Jetpack Compose?, you will reuse Task and sampleTasks() to render the task list.

How Do I Build My First Android App with Kotlin and Jetpack Compose?

In this first article of the Android with Kotlin and Jetpack Compose series, you will create Task Notes, a small app for keeping track of daily tasks. Today you will run the starter project and build the screen users see when their task list is empty. You will reuse this project throughout the series, all the way to preparing a release for Google Play.

Kotlin is the language you will use to write the app. Jetpack Compose is the toolkit you will use to describe what appears on the screen. For example, a Compose Text() call adds text to your interface.

1. Install Android Studio

Download the stable version of Android Studio and complete its setup wizard. Let it download the Android SDK and the recommended components. The first setup and build need an internet connection.

You can run the app on an Android emulator or on an Android phone. The emulator is a virtual Android device that runs on your computer.

2. Create the Task Notes project

  1. Select New Project from the welcome screen. If a project is already open, choose File > New > New Project.
  2. Under the phone and tablet templates, choose Empty Activity and click Next.
  3. Enter the following values and click Finish.
Setting Value
Name Task Notes
Package name org.kodejava.tasknotes
Minimum SDK API 24 (Android 7.0) for this tutorial
Build configuration language Kotlin DSL, if the wizard offers a choice

Use a package name under your own namespace if you plan to publish your own version. Android Studio normally uses the package name you enter here as the initial application ID. The minimum SDK determines the oldest Android version on which the app can be installed.

Wait for Gradle sync to finish. Gradle reads the project’s build configuration and downloads the libraries it needs. When the editor opens, find MainActivity.kt in the app module. With the sample package name, its path is app/src/main/java/org/kodejava/tasknotes/MainActivity.kt.

Reference: Create a project with Compose.

3. Run the generated app

To use an emulator, open Tools > Device Manager, create a virtual phone, and select a system image with API 24 or higher. Download the image if prompted. Select the virtual device in the toolbar and click Run.

To use a phone, enable Developer options and USB debugging, connect it with a USB data cable, and accept the debugging prompt on the phone. Select the phone in Android Studio and click Run.

Android Studio builds and installs the app on the selected device. Once the template screen opens, you can move on to editing it.

References: Run apps on the Android Emulator and Run apps on a hardware device.

4. Build the empty task screen

Replace the contents of MainActivity.kt with the following code. If you chose a different package name, keep your original package line and use the theme import and function name from your generated activity.

package org.kodejava.tasknotes

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import org.kodejava.tasknotes.ui.theme.TaskNotesTheme

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()

        setContent {
            TaskNotesTheme {
                Scaffold(modifier = Modifier.fillMaxSize()) { innerPadding ->
                    TaskNotesScreen(modifier = Modifier.padding(innerPadding))
                }
            }
        }
    }
}

@Composable
private fun TaskNotesScreen(modifier: Modifier = Modifier) {
    Column(
        modifier = modifier.fillMaxSize().padding(24.dp),
        verticalArrangement = Arrangement.spacedBy(8.dp)
    ) {
        Text(
            text = "Task Notes",
            style = MaterialTheme.typography.headlineMedium
        )
        Text(
            text = "No tasks yet.",
            style = MaterialTheme.typography.bodyLarge
        )
    }
}

@Preview(showBackground = true)
@Composable
private fun TaskNotesScreenPreview() {
    TaskNotesTheme {
        TaskNotesScreen()
    }
}

When Android creates MainActivity, it calls onCreate(). Inside that method, setContent { ... } supplies the activity’s Compose UI, and TaskNotesTheme provides the app’s colors and text styles.

@Composable marks a function that can describe UI using other composable functions. Here, TaskNotesScreen() uses a Column to stack two Text() elements vertically. The 8.dp value adds space between them. Android uses density-independent pixels, or dp, to keep layout sizes consistent across screens with different pixel densities.

The app draws edge to edge. Passing innerPadding from Scaffold to the screen keeps the text clear of the system bars. The screen adds another 24.dp of padding for its own layout.

5. Check the result

Click Run again. You should see Task Notes near the top of the screen, with No tasks yet. on the line below. To inspect the layout in Android Studio, open the Split or Design view and build or refresh the preview if prompted. The @Preview function renders the screen in the editor.

If the theme import is unresolved, open the generated ui/theme/Theme.kt and check its package and theme function name. If Compose imports are unresolved, check that you selected Empty Activity and that Gradle sync completed successfully.

Practice

Change the message to Your task list is empty. and increase the space between the title and the message from 8.dp to 16.dp. Check the preview, then run the app to see the same changes on your device.

Gradle dependencies

The Empty Activity template sets up the Compose build configuration and dependencies for this example. Keep the generated entries in app/build.gradle.kts and, if the project uses one, gradle/libs.versions.toml. The code uses Activity Compose, Compose Material 3, and Compose UI Tooling Preview. This article requires no additional dependencies.

Next in the series

In the next article, How Do I Use Kotlin to Model Tasks in an Android App?, you will create a Kotlin Task data class with an ID, a title, and a completion flag. You will use that model to create the sample tasks for the list screen.

How do I downgrade Android SDK emulator version?

I was trying to run Android Studio Emulator on my old 13-inch Mid 2012 MacBook Pro (Mac OS X Catalina, version 10.15.7). Every time I tried to start a Virtual Device it failed to start, it crashed all the time. Checking the idea.log, which located at $HOME/Library/Logs/Google/AndroidStudio2023.1/, give me some hints.

The log tells me that the current installed emulator was build for the newer version of MacBook Pro and newer Mac OS, in this case the Mac OS X 11.1. So to make the Android SDK Emulator run again on my MacBook Pro, I need to downgrade my Android emulator version.

Here are the clues from the log file:

2024-02-11 07:30:14,110 [7595298]   INFO - Emulator: Medium Phone API 27 - /Users/wayan/Library/Android/sdk/emulator/emulator -netdelay none -netspeed full -avd Medium_Phone_API_27 -qt-hide-window -grpc-use-token -idle-grpc-timeout 300
2024-02-11 07:30:14,200 [7595388]   INFO - Emulator: Medium Phone API 27 - Android emulator version 33.1.24.0 (build_id 11237101) (CL:N/A)
2024-02-11 07:30:14,200 [7595388]   INFO - Emulator: Medium Phone API 27 - Found systemPath /Users/wayan/Library/Android/sdk/system-images/android-27/google_apis_playstore/x86/
2024-02-11 07:30:15,424 [7596612]   INFO - Emulator: Medium Phone API 27 - dyld: Symbol not found: _vmnet_e
2024-02-11 07:30:15,428 [7596616]   INFO - Emulator: Medium Phone API 27 - nable_isolation_key
2024-02-11 07:30:15,429 [7596617]   INFO - Emulator: Medium Phone API 27 - Referenced
2024-02-11 07:30:15,429 [7596617]   INFO - Emulator: Medium Phone API 27 - from: /Users/wayan/Library/Android/sdk/emulator/qemu/darwin-x86_64/qemu-system-i386 (which was built for Mac OS X 11.1)
2024-02-11 07:30:15,429 [7596617]   INFO - Emulator: Medium Phone API 27 - Expected in: /System/Library/Frameworks/vmnet.framework/Versions/A/vmnet
2024-02-11 07:30:15,429 [7596617]   INFO - Emulator: Medium Phone API 27 - in /Users/wayan/Library/Android/sdk/emulator/qemu/darwin-x86_64/qemu-system-i386
2024-02-11 07:30:15,430 [7596618]   INFO - Emulator: Medium Phone API 27 - Process finished with exit code 134 (interrupted by signal 6: SIGABRT)
2024-02-11 07:30:15,431 [7596619] SEVERE - Emulator: Medium Phone API 27 - Emulator terminated with exit code 134
java.lang.Throwable: Emulator terminated with exit code 134
    at com.intellij.openapi.diagnostic.Logger.error(Logger.java:202)
    at com.android.tools.idea.avdmanager.EmulatorProcessHandler$ConsoleListener.onTextAvailable(EmulatorProcessHandler.kt:89)
    at jdk.internal.reflect.GeneratedMethodAccessor40.invoke(Unknown Source)

So these are the steps that I need to do to downgrade it:

  • Download an older version of Android Emulator, here is the link to Android Emulator archive: https://developer.android.com/studio/emulator_archive.
  • I download version 30.7.4.
  • Locate the current emulator directory, which is under my Android SDK installation directory at $HOME/Library/Android/sdk.
  • Rename the existing emulator directory from emulator to emulator_original.
  • Next, I unzip the downloaded emulator, emulator-darwin_x64-7324830.zip, and copy it to the same location where the original emulator was located.
  • In the SDK installation directory, run the following command xattr -dr com.apple.quarantine emulator/ from the terminal app to clear the quarantine attribute on the emulator package.
  • Copy the package.xml file from the emulator_original directory to the emulator directory.
  • Change the emulator version in the package.xml file, it located at the end of the file. It should look something like:
<revision><major>30</major><minor>7</minor><micro>4</micro></revision>

After downgrading the emulator, I restarted the Android Studio, and I can now start the emulator successfully and able to run and test my application in the old MacBook Pro again.

How do I format EditText for currency input in Android?

The following Android code snippet shows you how to customize the input value format of an EditText component for accepting currency number. To format the input value we will create a text watcher class called MoneyTextWatcher, this class implements of the android.text.TextWatcher interface.

In the MoneyTextWatcher class we implement the afterTextChanged(EditText s) method, in this method the currency formatting takes place by adding currency symbol before the digit on numbers.

To apply this text watcher class we call the addTextChangedListener() method of the EditText object of the currency input and pass an instance of MoneyTextWatcher. Below is the working example of the activity class and the text watcher.

package org.kodejava.android;

import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;

import java.math.BigDecimal;

public class MainActivity extends AppCompatActivity {
    private EditText editText;
    private TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        editText = findViewById(R.id.editText);
        editText.addTextChangedListener(new MoneyTextWatcher(editText));
        editText.setText("0");

        textView = findViewById(R.id.textView);
    }

    public void doGetValue(View view) {
        BigDecimal value = MoneyTextWatcher.parseCurrencyValue(editText.getText().toString());
        textView.setText(String.valueOf(value));
    }
}

When the EditText input is changed the afterTextChanged() method of the text watcher will be called. In this method we’ll take the input text and format the input value with currency symbol and a number, this is done by the NumberFormat.getCurrencyInstance() object.

The static helper method parseCurrencyValue() will get the number part of the EditText by removing the currency symbol and return the input number.

package org.kodejava.android;

import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.widget.EditText;

import java.lang.ref.WeakReference;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.NumberFormat;
import java.util.Locale;
import java.util.Objects;

public class MoneyTextWatcher implements TextWatcher {
    private static final Locale locale = new Locale("id", "ID");
    private static final DecimalFormat formatter = (DecimalFormat) NumberFormat.getCurrencyInstance(locale);
    private final WeakReference<EditText> editTextWeakReference;

    public MoneyTextWatcher(EditText editText) {
        editTextWeakReference = new WeakReference<>(editText);
        formatter.setMaximumFractionDigits(0);
        formatter.setRoundingMode(RoundingMode.FLOOR);

        DecimalFormatSymbols symbol = new DecimalFormatSymbols(locale);
        symbol.setCurrencySymbol(symbol.getCurrencySymbol() + " ");
        formatter.setDecimalFormatSymbols(symbol);
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
    }

    @Override
    public void afterTextChanged(Editable s) {
        EditText editText = editTextWeakReference.get();
        if (editText == null || editText.getText().toString().isEmpty()) {
            return;
        }
        editText.removeTextChangedListener(this);

        BigDecimal parsed = parseCurrencyValue(editText.getText().toString());
        String formatted = formatter.format(parsed);

        editText.setText(formatted);
        editText.setSelection(formatted.length());
        editText.addTextChangedListener(this);
    }

    public static BigDecimal parseCurrencyValue(String value) {
        try {
            String replaceRegex = String.format("[%s,.\\s]",
                    Objects.requireNonNull(formatter.getCurrency()).getSymbol(locale));
            String currencyValue = value.replaceAll(replaceRegex, "");
            currencyValue = "".equals(currencyValue) ? "0" : currencyValue;
            return new BigDecimal(currencyValue);
        } catch (Exception e) {
            Log.e("App", e.getMessage(), e);
        }
        return BigDecimal.ZERO;
    }
}

The following animation is the result of our code snippet above, and you can find to complete source code here: Android Currency EditText Example



How do I get Android Device ID or IMEI?

The following code snippets shows you how to get a Device ID of an Android phone. To be able to read the Device ID you need to update the AndroidManifest.xml file and add the READ_PHONE_STATE permission.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="org.kodejava.android">

    <uses-permission android:name="android.permission.READ_PHONE_STATE" />

    ...
    ...
</manifest>
package org.kodejava.android;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.util.Log;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

public class MainActivity extends AppCompatActivity {

    private static final int PERMISSIONS_READ_PHONE_STATE = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_PHONE_STATE}, PERMISSIONS_READ_PHONE_STATE);
        }

        String deviceId = null;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            deviceId = Settings.Secure.getString(getApplicationContext().getContentResolver(), Settings.Secure.ANDROID_ID);
        } else {
            TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
            if (telephonyManager.getImei() != null) {
                deviceId = telephonyManager.getImei();
            } else if (telephonyManager.getMeid() != null) {
                deviceId = telephonyManager.getMeid();
            }
        }

        Log.d("MyApp", "Device ID: " + deviceId);
    }
}