kotlin android app development course, building screens with Material Library

Hello! In this article, we will explore in detail how to create beautiful and functional user interfaces (UI) using Kotlin for Android app development, from the basics to intermediate level, especially utilizing Google’s Material Library.

1. What is Material Design?

Material Design is a design language announced by Google in 2014, created to enhance user experience (UX) and develop appealing apps. Material Design is consistent and provides intuitive UI elements, giving users a familiar feeling.

Key elements include color, typography, shadows, animations, etc., which provide information hierarchy and intuitive interactions.

2. Installing Material Components

First, to use Material Design components, you need to add the necessary libraries to your project. Add the following dependencies to your build.gradle file.

dependencies {
        implementation 'com.google.android.material:material:1.6.1'
    }

3. Constructing Basic Layout

The starting point of an Android app is typically a layout file named activity_main.xml. Let’s construct a basic layout using Material components.

<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.google.android.material.appbar.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <androidx.appcompat.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"/>

    </com.google.android.material.appbar.AppBarLayout>

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Material Design for Android App Development"/>
                
            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Click the button"/>

        </LinearLayout>

    </ScrollView>

</androidx.coordinatorlayout.widget.CoordinatorLayout>

4. Using Material Button and Text Field

Next, let’s create a form to gather input from the user using Material Button and Text Field.

<com.google.android.material.textfield.TextInputLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Enter your name">

        <com.google.android.material.textfield.TextInputEditText
            android:id="@+id/edit_name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>

    </com.google.android.material.textfield.TextInputLayout>

    <com.google.android.material.button.MaterialButton
        android:id="@+id/btn_submit"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Submit"/>

Handling User Input

Now, let’s write code to handle the input when the user clicks the button after entering text.

class MainActivity : AppCompatActivity() {

        private lateinit var editName: TextInputEditText
        private lateinit var btnSubmit: MaterialButton

        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)

            editName = findViewById(R.id.edit_name)
            btnSubmit = findViewById(R.id.btn_submit)

            btnSubmit.setOnClickListener {
                val name = editName.text.toString()
                Toast.makeText(this, "Entered name: $name", Toast.LENGTH_SHORT).show()
            }
        }
    }

5. Implementing Material Snippet Dialog

Let’s use a dialog to get additional information from the user. Here’s how to implement a Material dialog.

private fun showInputDialog() {
        val builder = AlertDialog.Builder(this)
        builder.setTitle("Input Information")
        
        val input = EditText(this)
        builder.setView(input)

        builder.setPositiveButton("OK") { _, _ -> 
            Toast.makeText(this, "Input value: ${input.text}", Toast.LENGTH_SHORT).show()
        }
        builder.setNegativeButton("Cancel") { dialog, _ -> dialog.cancel() }

        builder.show()
    }

6. Utilizing Material CardView

CardView is a great component that can effectively showcase a collection of information. Let’s learn how to display multiple pieces of information using CardView.

<androidx.cardview.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:cardElevation="4dp"
        app:cardCornerRadius="8dp">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="CardView Title"
                android:textStyle="bold"
                android:padding="16dp"/>

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="This is where the content of the card goes."
                android:padding="16dp"/>

        </LinearLayout>

    </androidx.cardview.widget.CardView>

7. Animations and Transition Effects with Material Design

Let’s learn how to implement animations and transition effects to provide visual impact. You can use the Transition API to apply animation effects during screen transitions.

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // Transition animation from the previous screen
        val transition = ChangeBounds()
        transition.duration = 300
        TransitionManager.beginDelayedTransition(findViewById(R.id.coordinatorLayout), transition)
    }

8. List Composed with Material Design

To effectively list information in an Android app, I will explain how to configure a list using RecyclerView.

class MyAdapter(private val items: List) : RecyclerView.Adapter() {

        inner class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
            val textView: TextView = itemView.findViewById(R.id.text_view)
        }

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
            val view = LayoutInflater.from(parent.context).inflate(R.layout.item_layout, parent, false)
            return MyViewHolder(view)
        }

        override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
            holder.textView.text = items[position]
        }

        override fun getItemCount() = items.size
    }

9. Conclusion

In this tutorial, we learned how to construct the UI of a basic Android app using Kotlin and Material Design components. With Material Design, you can conceive apps that are more intuitive and inviting for users.

Material Design offers a variety of components and functionalities, allowing you to combine them freely as needed. Continue to add more features, practice, and gain experience!

Thank you!

Learn Kotlin Android App Development, Types and Characteristics of Resources

When developing Android apps, resources are an essential element. Resources encompass various items ranging from UI components to logic, data, and more, helping developers and designers collaborate to enhance the quality of the app. In this tutorial, we will explore the different types and characteristics of resources used in Android.

1. What are Resources?

Resources are components of the application, including various attributes of the app, such as XML files, images, strings, etc. The Android platform enables multi-language support, support for various screen sizes and resolutions, and more through resources.

2. Types of Resources

The main types of resources used in Android are as follows:

  • String Resources: Manages strings used in the app. The strings.xml file within the values folder is used to support multiple languages. You can define string resources within this file.
  • Styles and Themes: Defines styles to maintain consistency in the UI and applies design elements to the entire app or specific activities. You manage this by creating a styles.xml file in the values folder.
  • Drawable Resources: Contains images and graphic files used in the app. Various formats are supported, including PNG, JPG, and XML-based vector images.
  • Layout Resources: XML files that define the placement of UI elements. These are used to compose the UI of Activities or Fragments. For example, you can create an activity_main.xml file in the res/layout folder to define the layout.
  • Value Resources: Defines values such as integers, floating-point numbers, and colors. This is managed through int.xml and colors.xml files in the values folder.
  • Animation Resources: Defines animations for UI elements. You can create XML files in the res/anim folder to use these resources.
  • Remote Resources: Refers to resources that are not used internally by the app but are provided externally. For example, this includes cases where online images or data are requested.

3. String Resources

String resources are typically one of the most commonly used resources. They are a powerful tool for supporting multiple languages. Here’s how to define and use string resources.

3.1 Defining String Resources


<resources>
    <string name="app_name">My Cool App</string>
    <string name="welcome_message">Welcome to my app!</string>
</resources>

3.2 Using String Resources

To use string resources, you can retrieve strings in an activity with the following code.


val appName = getString(R.string.app_name)
textView.text = appName

4. Styles and Themes

Styles and themes are used to maintain consistency in the design of UI elements. Here’s how to define styles.

4.1 Defining Styles


<style name="AppTheme">
    <item name="colorPrimary">#6200EE</item>
    <item name="colorPrimaryDark">#3700B3</item>
    <item name="colorAccent">#03DAC5</item>
</style>

4.2 Applying Themes

You create a template by invoking styles and set the theme for the app. This can be specified in the AndroidManifest.xml file.


<application
    android:theme="@style/AppTheme">

5. Drawable Resources

Drawable resources include various icons, images, and graphics in the UI. PNG, JPG, XML-based vector files, and more can be used.
Drawable resources are stored in the res/drawable folder and also support vector images through XML.

5.1 Using Drawable Resources

You can reference and use drawable resources as follows.


imageView.setImageResource(R.drawable.my_image)

6. Layout Resources

Layout resources define the placement of UI components. They are defined through XML files and can be set in Activities or Fragments.

6.1 Example of a Layout File


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/welcomeTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/welcome_message" />

    <Button
        android:id="@+id/startButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Start" />

</LinearLayout>

6.2 Setting the Layout

In an activity, the layout is set using the setContentView() method.


setContentView(R.layout.activity_main)

7. Value Resources

Value resources manage values such as colors, integers, and floating-point numbers. You can define them using colors.xml and integers.xml files in the res/values folder.

7.1 Defining Color Resources


<resources>
    <color name="colorPrimary">#6200EE</color>
    <color name="colorAccent">#03DAC5</color>
</resources>

7.2 Using Colors

You can access and use color values as follows.


val color = ContextCompat.getColor(this, R.color.colorPrimary)

8. Animation Resources

Animation resources add liveliness to UI elements. They are defined through XML files.

8.1 Example of Animation


<alpha xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromAlpha="0.0"
    android:toAlpha="1.0"
    android:duration="1000" />

8.2 Applying Animation

You can apply animations using the Animation class.


val animation = AnimationUtils.loadAnimation(this, R.anim.fade_in)
textView.startAnimation(animation)

9. Remote Resources

Remote resources are primarily used for requesting data through APIs. For example, you can retrieve JSON data from a server and display it in the UI.

9.1 Requesting Remote Data using Retrofit

The Retrofit library allows for easy HTTP requests. Here’s a simple example.


// Define the Retrofit service interface
interface ApiService {
    @GET("data")
    suspend fun getData(): Response>
}

// Create Retrofit instance
val retrofit = Retrofit.Builder()
    .baseUrl("https://api.example.com/")
    .addConverterFactory(GsonConverterFactory.create())
    .build()

val apiService = retrofit.create(ApiService::class.java)

9.2 Fetching Data and Displaying it in the UI


lifecycleScope.launch {
    val response = apiService.getData()
    if (response.isSuccessful) {
        val data = response.body()
        // Update the UI
    }
}

10. Conclusion and Summary

In Android app development, resources are a very important component. By utilizing various resources such as strings, styles, drawables, and layouts, you can support multiple languages, maintain consistency in the UI, and enhance the user experience. If you understand the methods and characteristics of each resource and can use them appropriately, more effective app development will be possible.

This tutorial explained the basic types of resources and how to use them. Understanding how to define, create, and utilize resources in detail will help you when developing real apps.

Now you can effectively use the necessary resources for Android app development with Kotlin! If anyone has questions or concerns, please leave a comment, and I will respond diligently.

course on Kotlin Android App Development, Resource Condition Setting

Android app development requires managing and utilizing various resources. In particular, it is essential to adjust resources conditionally based on different screen sizes, densities, languages, etc. This article will explain in detail how to set resource conditions in Android using Kotlin and provide opportunities for practical exercises with sample code.

1. What are Android Resources?

Android resources encompass all elements used in an app, including UI, strings, images, and other files. Resource management defines the appearance and behavior of the app, and efficiently managing these resources significantly impacts the app’s quality and user experience.

Types of Resources

  • Drawable: Resources that include images. They can be stored in multiple folders to support various resolutions.
  • Layout: XML format layout files that define the UI.
  • Strings: Files that contain string resources used in the application. Useful for multilingual support.
  • Colors: Resources for color definitions.

2. Importance of Setting Resource Conditions

Setting resource conditions is essential for providing an optimal user experience across various devices and situations. Android automatically selects resources based on specific conditions (e.g., screen size, dpi, language). This allows a single code base to cater to different environments.

Main Conditions

  • Screen Size: Divided into small, normal, large, xlarge, etc.
  • Screen Density: Categorized as ldpi, mdpi, hdpi, xhdpi, xxhdpi, xxxhdpi, etc.
  • Language: Resources can be adjusted to accommodate various languages for localization support.

3. How to Set Resource Conditions

In Android Studio, the method to define resources conditionally is as follows:

3.1. Resource Directory Structure

Resources generally follow this directory structure:

res/
├── drawable-hdpi/
│   └── image.png
├── drawable-mdpi/
│   └── image.png
├── values/
│   └── strings.xml
├── values-en/
│   └── strings.xml

With this directory structure, Android automatically selects the appropriate resources.

3.2. Resource Directory Example

Below is an example of setting image resources based on screen density. You just need to place the corresponding resolution image in each drawable directory.

res/
├── drawable-hdpi/
│   └── image.png // High-resolution image
├── drawable-mdpi/
│   └── image.png // Medium-resolution image
├── drawable-ldpi/
│   └── image.png // Low-resolution image

With this setup, the Android system will automatically select the appropriate image based on the device’s screen density.

3.3. String Resources

You can set up the strings.xml file for multilingual support as follows.



    App Name
    Welcome!

Save this file in the values-en folder, and the English resources should be saved in the values folder. In this case, the system will automatically select the appropriate resources based on language settings.

4. Multiple Qualification Conditions for Resource Selection

Android allows combining various qualification conditions to select resources. For instance, you can combine screen size, orientation, and language.

4.1. Example: Resource Settings Based on Screen Orientation

Different layouts can be set for portrait and landscape orientations. Define the basic layout in res/layout and define the landscape layout in res/layout-land.

res/
├── layout/
│   └── activity_main.xml // Portrait layout
├── layout-land/
│   └── activity_main.xml // Landscape layout

5. Utilizing Resources in Kotlin

There are various ways to access and utilize resources in Android apps. Below is a simple example using Kotlin.

5.1. Example of Using String Resources

Here is an example of using string resources.

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val welcomeMessage = getString(R.string.welcome_message)
        Toast.makeText(this, welcomeMessage, Toast.LENGTH_LONG).show()
    }
}

5.2. Example of Using Drawable Resources

Below is an example of using drawable resources.

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val imageView: ImageView = findViewById(R.id.imageView)
        imageView.setImageResource(R.drawable.image)
    }
}

6. Conclusion

Properly managing resources in Android apps is a crucial task. Using Kotlin makes this implementation easy, allowing you to set resources according to various conditions. I hope the explanations and sample code above provide a foundation for resource condition settings in Android using Kotlin. In the future, we will cover more in-depth topics and advanced techniques.

Continue to follow this series to gain more information about Android app development and make your apps great!

KOTLIN ANDROID APP DEVELOPMENT COURSE, RECYCLE VIEW – LIST SCREEN CONFIGURATION

User interface (UI) is a very important element in Android app development. The UI is what users encounter first when using the app, and it determines the user’s experience and satisfaction. In this tutorial, I will explain in detail how to create a list screen using Android’s RecyclerView. RecyclerView is a powerful UI component designed to efficiently display various amounts of data.

1. What is RecyclerView?

RecyclerView is the latest UI component included in the Android Support Library, and it is a powerful tool for efficiently displaying large amounts of data. It is similar to ListView but is differentiated by its superior performance and flexibility. RecyclerView uses the ViewHolder pattern to optimize UI performance and supports asynchronous scrolling through various layout managers.

2. Components of RecyclerView

  • Adapter: Manages the set of data to be displayed in the RecyclerView and binds the data to the view holders.
  • ViewHolder: Holds the views representing each item in the RecyclerView and optimizes memory usage.
  • LayoutManager: Determines how items in the RecyclerView are laid out and handles vertical/horizontal scrolling.

3. Creating a List Screen using RecyclerView

Now, let’s configure the list screen using RecyclerView through actual code. In this example, we will implement a simple contact list.

3.1 Project Setup

Create a new Android Studio project and add the RecyclerView dependency to the Gradle file.

implementation "androidx.recyclerview:recyclerview:1.2.1"

3.2 Layout Configuration

Now, let’s write the main layout XML file to display the RecyclerView.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="16dp"
        android:clipToPadding="false"/>
</RelativeLayout>

3.3 Creating Data Model Class

Write a data model class to hold contact information.

data class Contact(val name: String, val phone: String)

3.4 Writing the ViewHolder Class

Implement the ViewHolder to structure the UI for each item.

class ContactViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
    val nameTextView: TextView = itemView.findViewById(R.id.nameTextView)
    val phoneTextView: TextView = itemView.findViewById(R.id.phoneTextView)
}

3.5 Implementing the Adapter Class

Connect RecyclerView with the data source through the Adapter.

class ContactAdapter(private val contacts: List) : RecyclerView.Adapter<ContactViewHolder>() {
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ContactViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.item_contact, parent, false)
        return ContactViewHolder(view)
    }

    override fun onBindViewHolder(holder: ContactViewHolder, position: Int) {
        val contact = contacts[position]
        holder.nameTextView.text = contact.name
        holder.phoneTextView.text = contact.phone
    }

    override fun getItemCount(): Int {
        return contacts.size
    }
}

3.6 Linking RecyclerView

Link the RecyclerView and Adapter in the main activity.

class MainActivity : AppCompatActivity() {
    private lateinit var recyclerView: RecyclerView
    private lateinit var contactAdapter: ContactAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        recyclerView = findViewById(R.id.recyclerView)
        recyclerView.layoutManager = LinearLayoutManager(this)

        val contacts = listOf(
            Contact("John Doe", "123-456-7890"),
            Contact("Jane Smith", "987-654-3210"),
            Contact("Joe Bloggs", "543-210-9876")
        )

        contactAdapter = ContactAdapter(contacts)
        recyclerView.adapter = contactAdapter
    }
}

4. Going Further: Implementing Additional Features

Now that the basic RecyclerView implementation is complete, let’s implement some additional features to enhance the application.

4.1 Adding Click Listeners

Add click listeners to each list item to perform additional actions when clicked.

override fun onBindViewHolder(holder: ContactViewHolder, position: Int) {
    val contact = contacts[position]
    holder.nameTextView.text = contact.name
    holder.phoneTextView.text = contact.phone

    holder.itemView.setOnClickListener {
        Toast.makeText(holder.itemView.context, "Clicked: ${contact.name}", Toast.LENGTH_SHORT).show()
    }
}

4.2 Creating Item Layout

Design the item layout to display contact information.

<?xml version="1.0" encoding="utf-8" ?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:padding="8dp">

    <TextView
        android:id="@+id/nameTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="18sp"
        android:textStyle="bold"/>

    <TextView
        android:id="@+id/phoneTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="14sp"/>

</LinearLayout>

4.3 Item Deletion Feature

You can implement a feature to delete specific items from the data list. Refer to the following code.

class ContactAdapter(private val contacts: MutableList) : RecyclerView.Adapter<ContactViewHolder>() {
    // ...

    // Add item removal method
    fun removeItem(position: Int) {
        contacts.removeAt(position)
        notifyItemRemoved(position)
    }
}

Now let’s add a feature to delete items when they are long pressed.

holder.itemView.setOnLongClickListener {
    removeItem(position)
    true
}

5. Conclusion

In this tutorial, we learned how to configure RecyclerView in an Android application using Kotlin. RecyclerView is a powerful tool capable of efficiently displaying large amounts of data and has significant advantages in flexibility and performance. By combining various components and features, you can build complex UIs tailored to real user experiences.

Now, based on what you’ve learned in this tutorial, try to integrate RecyclerView into your actual apps to manage and display various data.

References

Kotlin Android app development course, storing data in a database

1. Introduction

Data management is an essential element in modern application development. The database for storing user information or the state of the application is becoming increasingly important. In Android applications, the use of databases is essential for effectively managing user data. In this course, we will cover how to store data in a database using Kotlin.

2. Types of Databases

There are various databases that can be used in Android, among which the most commonly used are as follows:

  • SQLite: A lightweight database built into the Android platform that uses SQL language to manage data.
  • Room: A wrapper library for SQLite, allowing interaction with SQLite in an object-oriented manner.
  • Firebase Realtime Database: A cloud-based database by Google that provides real-time data synchronization and offline support.

This course will focus on SQLite and Room.

3. SQLite Database

SQLite is a simple and efficient way to store data locally. It allows for quick access to requested data in component-based Android applications. To use the SQLite database, the following key steps must be followed.

3.1. SQLiteOpenHelper Class

SQLiteOpenHelper is a class for creating and managing database versions. It helps manage the database.

Below is a simple implementation example of SQLiteOpenHelper:

                
                class MyDatabaseHelper(context: Context) : SQLiteOpenHelper(context, DATABASE_NAME, null, DATABASE_VERSION) {
                    override fun onCreate(db: SQLiteDatabase) {
                        val createTableSQL = "CREATE TABLE ${TABLE_NAME} (" +
                                "${COLUMN_ID} INTEGER PRIMARY KEY AUTOINCREMENT, " +
                                "${COLUMN_NAME} TEXT)"
                        db.execSQL(createTableSQL)
                    }
            
                    override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
                        db.execSQL("DROP TABLE IF EXISTS $TABLE_NAME")
                        onCreate(db)
                    }
                }
                
            

3.2. Inserting, Retrieving, Updating, and Deleting Data

Now, let’s learn how to insert, read, update, and delete data in the database.

Inserting Data

                
                fun insertData(name: String) {
                    val db = this.writableDatabase
                    val values = ContentValues().apply {
                        put(COLUMN_NAME, name)
                    }
                    db.insert(TABLE_NAME, null, values)
                    db.close()
                }
                
            

Retrieving Data

                
                fun getData(): List {
                    val dataList = mutableListOf()
                    val db = this.readableDatabase
                    val cursor: Cursor = db.rawQuery("SELECT * FROM $TABLE_NAME", null)
                    if (cursor.moveToFirst()) {
                        do {
                            val name = cursor.getString(cursor.getColumnIndex(COLUMN_NAME))
                            dataList.add(name)
                        } while (cursor.moveToNext())
                    }
                    cursor.close()
                    db.close()
                    return dataList
                }
                
            

Updating Data

                
                fun updateData(id: Int, newName: String) {
                    val db = this.writableDatabase
                    val values = ContentValues().apply {
                        put(COLUMN_NAME, newName)
                    }
                    db.update(TABLE_NAME, values, "$COLUMN_ID = ?", arrayOf(id.toString()))
                    db.close()
                }
                
            

Deleting Data

                
                fun deleteData(id: Int) {
                    val db = this.writableDatabase
                    db.delete(TABLE_NAME, "$COLUMN_ID = ?", arrayOf(id.toString()))
                    db.close()
                }
                
            

4. Room Database

Room is a library that provides a simpler and more flexible way to access databases. It reduces the amount of database-related code and helps to use the database more safely. Room consists of three main components:

  • Entity: Represents a table in the database.
  • DAO (Data Access Object): Defines methods for accessing the database.
  • Database: The Room database class.

4.1. Defining Entity Classes

Defining an Entity in Room is akin to designing a table. Below is a simple example of a User Entity:

                
                @Entity(tableName = "user_table")
                data class User(
                    @PrimaryKey(autoGenerate = true) val id: Int = 0,
                    @ColumnInfo(name = "name") val name: String
                )
                
            

4.2. Defining DAO Interfaces

DAO defines methods to perform CRUD (Create, Read, Update, Delete) operations on the database:

                
                @Dao
                interface UserDao {
                    @Insert
                    suspend fun insert(user: User)
                    
                    @Query("SELECT * FROM user_table")
                    suspend fun getAllUsers(): List
                    
                    @Update
                    suspend fun update(user: User)
                    
                    @Delete
                    suspend fun delete(user: User)
                }
                
            

4.3. Defining RoomDatabase Class

The RoomDatabase class allows for the instantiation of DAO and the creation of the database:

                
                @Database(entities = [User::class], version = 1)
                abstract class UserDatabase : RoomDatabase() {
                    abstract fun userDao(): UserDao
                    
                    companion object {
                        @Volatile
                        private var INSTANCE: UserDatabase? = null

                        fun getDatabase(context: Context): UserDatabase {
                            return INSTANCE ?: synchronized(this) {
                                val instance = Room.databaseBuilder(
                                    context.applicationContext,
                                    UserDatabase::class.java,
                                    "user_database"
                                ).build()
                                INSTANCE = instance
                                instance
                            }
                        }
                    }
                }
                
            

4.4. Manipulating Data

Using the Room database, here’s how you can insert, retrieve, update, and delete data:

Inserting Data

                
                private fun insertUser(user: User) {
                    CoroutineScope(Dispatchers.IO).launch {
                        val db = UserDatabase.getDatabase(context)
                        db.userDao().insert(user)
                    }
                }
                
            

Retrieving Data

                
                private fun getAllUsers() {
                    CoroutineScope(Dispatchers.IO).launch {
                        val db = UserDatabase.getDatabase(context)
                        val users = db.userDao().getAllUsers()
                    }
                }
                
            

Updating Data

                
                private fun updateUser(user: User) {
                    CoroutineScope(Dispatchers.IO).launch {
                        val db = UserDatabase.getDatabase(context)
                        db.userDao().update(user)
                    }
                }
                
            

Deleting Data

                
                private fun deleteUser(user: User) {
                    CoroutineScope(Dispatchers.IO).launch {
                        val db = UserDatabase.getDatabase(context)
                        db.userDao().delete(user)
                    }
                }
                
            

5. Conclusion

In this course, we learned how to utilize databases in Android apps using Kotlin. We understood the advantages and disadvantages of both SQLite and Room, and learned how to store and manage data in an application through concrete implementation examples. Now, we hope you can use these techniques to effectively manage user data and enhance the functionality of your app.