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

Кotlin Android App Development Course, Drawer Layout – Side Screen Configuration

While developing Android applications, there are many UI components that help users seamlessly navigate through various menus and screens within the application. Among them, Drawer Layout is a side menu that users can access by swiping the edge of the screen or clicking a specific button, and it is commonly used in many Android apps. In this article, I will explain in detail how to create a simple Android app using Drawer Layout with Kotlin.

What is Drawer Layout?

Drawer Layout essentially provides a menu that users can pull from the left or right side of the screen by swiping or clicking a button. This menu generally includes multiple options or pages, aiding users in navigating through the application intuitively.

Components of Drawer Layout

Drawer Layout consists of the following main elements:

  • DrawerLayout: The layout that contains the drawer.
  • NavigationView: The component that defines menu items inside the drawer.
  • MainActivity: The activity that forms the main screen.

Implementing Drawer Layout

Now, let’s implement the Drawer Layout directly. You can set up the project and write the code following the steps below.

Step 1: Create a New Android Project

Open Android Studio and create a new project. Select "Empty Activity" or "Basic Activity". Choose Kotlin and set the project name.

Step 2: Modify the build.gradle File

You need to add the necessary dependencies to use Drawer Layout and Navigation View. Add the following to your app-level build.gradle file:

dependencies {
    implementation 'androidx.drawerlayout:drawerlayout:1.1.1'
    implementation 'com.google.android.material:material:1.4.0'
}

Step 3: Configure Layout

Now, open the activity_main.xml file and configure the Drawer Layout.

<androidx.drawerlayout.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <FrameLayout
        android:id="@+id/content_frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
       <!-- Area for main content -->
    </FrameLayout>

    <com.google.android.material.navigation.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start" 
        app:menu="@menu/drawer_view">
    </com.google.android.material.navigation.NavigationView>

</androidx.drawerlayout.widget.DrawerLayout>

Step 4: Add Menu Resources

Now you need to create an XML file to define the drawer menu items. Create a file named drawer_view.xml under the res/menu/ directory and write as follows:

<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@+id/nav_home"
        android:title="Home" />
    <item
        android:id="@+id/nav_gallery"
        android:title="Gallery" />
    <item
        android:id="@+id/nav_slideshow"
        android:title="Slideshow" />
</menu>

Step 5: Modify MainActivity

Now, in MainActivity.kt, you need to initialize the Drawer Layout and handle menu item click events. Write the code as follows:

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.drawerlayout.widget.DrawerLayout
import com.google.android.material.navigation.NavigationView
import android.view.MenuItem
import android.widget.Toast

class MainActivity : AppCompatActivity() {
    private lateinit var drawerLayout: DrawerLayout
    private lateinit var navigationView: NavigationView

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

        drawerLayout = findViewById(R.id.drawer_layout)
        navigationView = findViewById(R.id.nav_view)

        navigationView.setNavigationItemSelectedListener { menuItem ->
            when (menuItem.itemId) {
                R.id.nav_home -> {
                    Toast.makeText(this, "Home Clicked", Toast.LENGTH_SHORT).show()
                }
                R.id.nav_gallery -> {
                    Toast.makeText(this, "Gallery Clicked", Toast.LENGTH_SHORT).show()
                }
                R.id.nav_slideshow -> {
                    Toast.makeText(this, "Slideshow Clicked", Toast.LENGTH_SHORT).show()
                }
            }
            drawerLayout.closeDrawers() // Close the drawer after clicking
            true
        }
    }
}

Step 6: Apply and Run Drawer Layout

All setups are complete. Now you can run the app and swipe from the left edge of the screen or click the top hamburger menu to open the drawer. Clicking on the menu items will display the name of the item in a toast message.

Benefits and Considerations of Drawer Layout

Drawer Layout has the following benefits:

  • Provides various navigation options
  • Simplifies user experience
  • Keeps the design clean

However, there are also some considerations:

  • On mobile devices, space must be used efficiently on small screens.
  • Considering user experience, menu items should be concise and intuitive.

Conclusion

In this article, we thoroughly examined how to implement Drawer Layout using Kotlin. Drawer Layout is an essential UI element that helps users navigate easily within an application. By utilizing this layout, you can provide a better user experience for your app. Try creating your own Drawer Layout by setting various options and designs.

Additional Resources

If you want more information, you can refer to the following resources:

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.