Building a Todo List App with Room Database in Android

温柔守护 2021-11-02 ⋅ 14 阅读

In this tutorial, we will learn how to build a simple Todo List App with Room Database in Android. The Todo List App will allow users to create, read, update, and delete their todos.

Introduction

Room Database is a powerful and efficient ORM (Object Relational Mapping) library provided by Android Jetpack. It provides an abstraction layer over SQLite to allow for more robust database access while providing compile-time checks of queries.

Prerequisites

To follow along with this tutorial, make sure you have the following:

  • Android Studio installed on your machine
  • Basic knowledge of Kotlin or Java
  • Basic understanding of Android development

Setting up the Project

  1. Open Android Studio and create a new project.
  2. Choose an appropriate project name and package name.
  3. Select your desired minimum SDK version.
  4. Choose Kotlin or Java as the programming language.

Adding Room Database to the Project

  1. Open your app-level build.gradle file.
  2. Add the following dependencies:
implementation "androidx.room:room-runtime:2.3.0"
kapt "androidx.room:room-compiler:2.3.0"
  1. Sync your project to download the dependencies.

Creating the Todo Entity

  1. Create a new Kotlin or Java class called Todo.
  2. Add the following code to define the Todo entity:
@Entity(tableName = "todos")
data class Todo(
    @PrimaryKey(autoGenerate = true)
    val id: Long = 0,
    val title: String,
    val description: String,
    val date: Long,
    val completed: Boolean = false
)

Creating the Todo DAO (Data Access Object)

  1. Create a new Kotlin or Java interface called TodoDao.
  2. Add the following code to define the TodoDao interface:
@Dao
interface TodoDao {
    @Insert
    suspend fun add(todo: Todo)

    @Update
    suspend fun update(todo: Todo)

    @Delete
    suspend fun delete(todo: Todo)

    @Query("SELECT * FROM todos")
    suspend fun getAll(): List<Todo>
}

Creating the Todo Database

  1. Create a new Kotlin or Java abstract class called TodoDatabase.
  2. Extend the RoomDatabase class and annotate it with @Database.
  3. Add the following code to define the TodoDatabase:
@Database(entities = [Todo::class], version = 1)
abstract class TodoDatabase : RoomDatabase() {
    abstract fun todoDao(): TodoDao
}

Initializing the Todo Database

  1. Create a new Kotlin or Java Singleton class called TodoDatabaseInitializer.
  2. Add the following code to define the TodoDatabaseInitializer:
object TodoDatabaseInitializer {
    private const val DATABASE_NAME = "todo_database"

    fun initialize(context: Context): TodoDatabase {
        return Room.databaseBuilder(context, TodoDatabase::class.java, DATABASE_NAME)
            .fallbackToDestructiveMigration()
            .build()
    }
}

Creating the Todo Repository

  1. Create a new Kotlin or Java class called TodoRepository.
  2. Add the following code to define the TodoRepository:
class TodoRepository(private val todoDao: TodoDao) {
    suspend fun add(todo: Todo) {
        todoDao.add(todo)
    }

    suspend fun update(todo: Todo) {
        todoDao.update(todo)
    }

    suspend fun delete(todo: Todo) {
        todoDao.delete(todo)
    }

    suspend fun getAll(): List<Todo> {
        return todoDao.getAll()
    }
}

Building the Todo List App

  1. Create a new Kotlin or Java activity or fragment.
  2. Initialize the TodoDatabase using the TodoDatabaseInitializer.
val database = TodoDatabaseInitializer.initialize(applicationContext)
  1. Create a new instance of the TodoRepository.
val repository = TodoRepository(database.todoDao())
  1. Use the repository methods to perform CRUD operations on the Todo entity.
val todo = Todo(
    title = "Complete Room Database tutorial",
    description = "Build a Todo List App with Room Database",
    date = System.currentTimeMillis()
)

repository.add(todo)
repository.getAll()
// Update and delete operations can also be performed using the repository

Conclusion

In this tutorial, we learned how to build a Todo List App with Room Database in Android. We explored the steps involved in creating the Todo entity, Todo DAO, Todo Database, Todo Repository, and building the Todo List App. Room Database provides a convenient way to handle database operations in Android applications.


全部评论: 0

    我有话说: