How to Build a Grocery Android App using MVVM and Room Database?
Last Updated :
16 Aug, 2024
In this article, we are going to build a grocery application in android using android studio. Many times we forget to purchase things that we want to buy, after all, we can’t remember all the items, so with the help of this app, you can note down your grocery items that you are going to purchase, by doing this you can’t forget any items that you want to purchase. A sample image is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Kotlin language.

In this project, we are using MVVM (Model View ViewModel) for architectural patterns, Room for database, Coroutines and RecyclerView to display the list of items. Before jumping to the project let’s understand these terms.
MVVM (Model View ViewModel)
MVVM architecture in android is used to give structure to the project’s code and understand code easily. MVVM is an architectural design pattern in android. MVVM treat Activity classes and XML files as View. This design pattern completely separate UI from its logic. Here is an image to quickly understand MVVM.

After seeing this image if you don’t understand how it will work then don’t worry as we will write the code we understand it completely.
ROOM DataBase
Room persistence library is a database management library and it is used to store the data of apps like grocery item name, grocery item quantity, and grocery item price. Room is a cover layer on SQLite which helps to perform the operation on the database easily.
RecycleView
RecyclerView is a container and it is used to display the collection of data in a large amount of data set that can be scrolled very effectively by maintaining a limited number of views.
Coroutines
Coroutines are a lightweight thread, we use a coroutine to perform an operation on other threads, by this our main thread doesn’t block and our app doesn’t crash.
Step by Step Implementation
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language.
Step 2: Before going to the coding section first you have to do some pre-task
Before going to the coding part first add these libraries in your gradle file and also apply the plugin as ‘kotlin-kapt’. To add these library go to Gradle Scripts > build.gradle(Module:app).
Applying Kotlin Kapt plugin: To apply kotlin-kapt plugin, add this lines in your plugins block
id(“kotlin-kapt”)
After adding kotlin-kapt plygin successfully, add the dependencies
val roomVersion = “2.6.1”
val lifecycleVersion = “2.2.0”
// Room and Architectural Components
implementation(“androidx.room:room-runtime:$roomVersion”)
implementation(“androidx.legacy:legacy-support-v4:1.0.0”)
implementation(“androidx.lifecycle:lifecycle-extensions:2.2.0”)
implementation(“androidx.lifecycle:lifecycle-viewmodel-ktx:2.8.4”)
implementation(“androidx.room:room-ktx:2.6.1”)
kapt(“androidx.room:room-compiler:$roomVersion”)
// Coroutines
implementation(“org.jetbrains.kotlinx:kotlinx-coroutines-core:1.7.3”)
implementation(“org.jetbrains.kotlinx:kotlinx-coroutines-android:1.7.3”)
// New Material Design
implementation(“com.google.android.material:material:1.12.0”)
// ViewModel
implementation(“androidx.lifecycle:lifecycle-extensions:$lifecycleVersion”)
implementation(“androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycleVersion”)
kapt(“androidx.lifecycle:lifecycle-compiler:$lifecycleVersion”)
Below is the complete code for the build.gradle(:app) file.
Kotlin
plugins {
alias(libs.plugins.android.application)
alias(libs.plugins.jetbrains.kotlin.android)
id("kotlin-kapt")
}
android {
namespace = "com.ishaanbhela.myapplication"
compileSdk = 34
defaultConfig {
applicationId = "com.ishaanbhela.myapplication"
minSdk = 26
targetSdk = 34
versionCode = 1
versionName = "1.0"
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
isMinifyEnabled = false
proguardFiles(
getDefaultProguardFile("proguard-android-optimize.txt"),
"proguard-rules.pro"
)
}
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = "1.8"
}
}
dependencies {
implementation(libs.androidx.core.ktx)
implementation(libs.androidx.appcompat)
implementation(libs.material)
implementation(libs.androidx.activity)
implementation(libs.androidx.constraintlayout)
testImplementation(libs.junit)
androidTestImplementation(libs.androidx.junit)
androidTestImplementation(libs.androidx.espresso.core)
val roomVersion = "2.6.1"
val lifecycleVersion = "2.2.0"
// Room and Architectural Components
implementation("androidx.room:room-runtime:$roomVersion")
implementation("androidx.legacy:legacy-support-v4:1.0.0")
implementation("androidx.lifecycle:lifecycle-extensions:2.2.0")
implementation("androidx.lifecycle:lifecycle-viewmodel-ktx:2.8.4")
implementation("androidx.room:room-ktx:2.6.1")
kapt("androidx.room:room-compiler:$roomVersion")
// Coroutines
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.7.3")
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.7.3")
// New Material Design
implementation("com.google.android.material:material:1.12.0")
// ViewModel
implementation("androidx.lifecycle:lifecycle-extensions:$lifecycleVersion")
implementation("androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycleVersion")
kapt("androidx.lifecycle:lifecycle-compiler:$lifecycleVersion")
}
Below is the code for the strings.xml file. Here we have added the necessary strings that we are going to use in our project.
XML
<resources>
<string name="app_name">Fresh Basket</string>
<!-- TODO: Remove or change this placeholder text -->
<string name="hello_blank_fragment">Hello blank fragment</string>
<string name="itemName">Banana</string>
<string name="itemQuantity">35</string>
<string name="itemPrice">250Rs</string>
<string name="totalCost">20</string>
<string name="totalCostTitle">Total Cost</string>
<string name="title">Add Items to your cart</string>
<string name="etItem">Item</string>
<string name="etQuantity">Quantity</string>
<string name="etPrice">Price</string>
<string name="save">Save</string>
<string name="cancel">Cancel</string>
</resources>
Below is the code for the colors.xml file. Here we have added the necessary colors that we are going to use in our project.
XML
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="colorPrimary">#0AD042</color>
<color name="colorPrimaryDark">#03551A</color>
<color name="colorAccent">#03DAC5</color>
<color name="black">#000000</color>
<color name="white">#ffffff</color>
</resources>
Step 3: Implement room database
a) Entities class
The entities class contains all the columns in the database and it should be annotated with @Entity(tablename = “Name of table”). Entity class is a data class. And @Column info annotation is used to enter column variable name and datatype. We will also add Primary Key for auto-increment. Go to app > java > com.example.application-name. Right-click on com.example.application-name go to new and create Kotlin file/class and name the file as GroceryEntities. See the code below to completely understand and implement.
Kotlin
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
// This is a data class which store data.
// Entities class create a table in database,
// in our database we will create three column
@Entity(tableName = "grocery_items")
data class GroceryItems(
// create itemName variable to
// store grocery items.
@ColumnInfo(name = "itemName")
var itemName: String,
// create itemQuantity variable
// to store grocery quantity.
@ColumnInfo(name = "itemQuantity")
var itemQuantity: Int,
// create itemPrice variable to
// store grocery price.
@ColumnInfo(name = "itemPrice")
var itemPrice: Int
) {
// Primary key is a unique key
// for different database.
@PrimaryKey(autoGenerate = true)
var id: Int? = null
}
b) Dao Interface
The Dao is an interface in which we create all the functions that we want to implement on the database. This interface also annotated with @Dao. Now we will create a function using suspend function which is a coroutines function. Here we create three functions, First is the insert function to insert items in the database and annotated with @Insert, Second is for deleting items from the database annotated with @Delete and Third is for getting all items annotated with @Query. Go to the app > java > com.example.application-name . Right-click on com.example.application-name go to new and create Kotlin file/class and name the file as GroceryDao. See the code below to implement.
Kotlin
import androidx.lifecycle.LiveData
import androidx.room.*
import com.example.grocerylist.Database.Entity.GroceryItems
// This class is used to create
// function for database.
@Dao
interface GroceryDao {
// Insert function is used to
// insert data in database.
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insert(item: GroceryItems)
// Delete function is used to
// delete data in database.
@Delete
suspend fun delete(item: GroceryItems)
// getAllGroceryItems function is used to get
// all the data of database.
@Query("SELECT * FROM grocery_items")
fun getAllGroceryItems(): LiveData<List<GroceryItems>>
}
c) Database class
Database class annotated with @Database(entities = [Name of Entity class.class], version = 1) these entities are the entities array list all the data entities associating with the database and version shows the current version of the database. This database class inherits from the Room Database class. In GroceryDatabase class we will make an abstract method to get an instance of DAO and further use this method from the DAO instance to interact with the database. See the below code to implement. Go to the app > java > com.example.application-name. Right-click on com.example.application-name go to new and create Kotlin file/class as GroceryDatabase. See the code below to implement.
Kotlin
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import com.example.grocerylist.Database.Entity.GroceryItems
@Database(entities = [GroceryItems::class], version = 1)
abstract class GroceryDatabase : RoomDatabase() {
abstract fun getGroceryDao(): GroceryDao
companion object {
@Volatile
private var instance: GroceryDatabase? = null
private val LOCK = Any()
operator fun invoke(context: Context) = instance ?: synchronized(LOCK) {
instance ?: createDatabase(context).also {
instance = it
}
}
private fun createDatabase(context: Context) =
Room.databaseBuilder(context.applicationContext, GroceryDatabase::class.java, "GroceryDatabase.db").build()
}
}
Step 4: Now we will implement the architectural structure in the app
a) Repository class
The repository is one of the design structures. The repository class gives the data to the ViewModel class and then the ViewModel class uses that data for Views. The repository will choose the appropriate data locally or on the network. Here in our Grocery Repository class data fetch locally from the Room database. We will add constructor value by creating an instance of the database and stored in the db variable in the Grocery Repository class. Go to the app > java > com.example.application-name. Right-click on com.example.application-name go to new and create Kotlin file/class as GroceryRepository. See the code below to implement.
Kotlin
package com.example.grocerylist.Database
import com.example.grocerylist.Database.Entity.GroceryItems
class GroceryRepository(private val db: GroceryDatabase) {
suspend fun insert(item: GroceryItems) = db.getGroceryDao().insert(item)
suspend fun delete(item: GroceryItems) = db.getGroceryDao().delete(item)
fun allGroceryItems() = db.getGroceryDao().getAllGroceryItems()
}
Go to app > java > com.example.application-name. Right-click on com.example.application-name go to new and create a new Package called UI and then right-click on UI package and create a Kotlin file/class. See the code below to implement.
b) ViewModel class
ViewModel class used as an interface between View and Data. Grocery View Model class inherit from View Model class and we will pass constructor value by creating instance variable of Repository class and stored in repository variable. As we pass the constructor in View Model we have to create another class which is a Factory View Model class. Go to app > java > com.example.application-name > UI. Right-click on the UI package and create a Kotlin file/class and name the file as GroceryViewModel. See the below code.
Kotlin
import androidx.lifecycle.ViewModel
import com.example.grocerylist.Database.Entity.GroceryItems
import com.example.grocerylist.Database.GroceryRepository
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
class GroceryViewModel(private val repository: GroceryRepository) : ViewModel() {
// In coroutines thread insert item in insert function.
fun insert(item: GroceryItems) = GlobalScope.launch {
repository.insert(item)
}
// In coroutines thread delete item in delete function.
fun delete(item: GroceryItems) = GlobalScope.launch {
repository.delete(item)
}
//Here we initialized allGroceryItems function with repository
fun allGroceryItems() = repository.allGroceryItems()
}
c) Factory ViewModel class
We will inherit the Grocery ViewModel Factory class from ViewModelProvider.NewInstanceFactory and again pass constructor value by creating instance variable of Grocery Repository and return GroceryViewModel(repository). Go to the app > java > com.example.application-name > UI. Right-click on the UI package and create a Kotlin file/class name it GroceryViewModelFactory. See the below code to understand.
Kotlin
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.example.grocerylist.Database.GroceryRepository
class GroceryViewModelFactory(private val repository: GroceryRepository):ViewModelProvider.NewInstanceFactory() {
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
return GroceryViewModel(repository) as T
}
}
Step 5: Now let’s jump into the UI part
In the activity_main.xml file, we will add two ImageView, RecyclerView, and Button after clicking this button a DialogBox open and in that dialog box user can enter the item name, item quantity, and item price. Refer to the following code.
XML
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
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:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
android:orientation="vertical"
tools:context=".UI.MainActivity">
<!-- To create a app bar with logo image. -->
<ImageView
android:id="@+id/imageView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:src="@drawable/logo"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0" />
<!-- In this image view we will add a title image -->
<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="35dp"
android:src="@drawable/title"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.497"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/imageView2"
app:layout_constraintVertical_bias="0.0" />
<!-- Recycler View to display list -->
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/rvList"
android:layout_width="match_parent"
android:layout_height="470dp"
android:background="@color/white"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/imageView"
app:layout_constraintVertical_bias="1.0">
</androidx.recyclerview.widget.RecyclerView>
<!-- This button is used to open dialog box in
which user can enter grocery items -->
<Button
android:id="@+id/btnAdd"
android:layout_width="60dp"
android:layout_height="wrap_content"
android:background="@drawable/button"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.954"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/imageView"
app:layout_constraintVertical_bias="0.969" />
</androidx.constraintlayout.widget.ConstraintLayout>
Output of XML Code:
Step 6: Let’s implement RecyclerView. Now we will code the UI part of the row in the list. Go to app > res > layout. Right-click on layout, go to new, and then add a Layout Resource File and name it as groceryadapter. See the XML code of the groceryadapter.xml file.
XML
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
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="125dp"
android:background="@drawable/adapter1">
<!-- To display item name in recycler view -->
<!-- To display item quantity -->
<TextView
android:id="@+id/txtItemName"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="50dp"
android:layout_marginEnd="15dp"
android:fontFamily="@font/rokkitt"
android:text="@string/itemName"
android:textColor="@color/white"
android:textSize="35sp"
app:flow_verticalBias="0.0"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="@+id/txtItemQuantity"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.275" />
<TextView
android:id="@+id/txtItemQuantity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="34dp"
android:layout_marginRight="34dp"
android:layout_marginBottom="26dp"
android:layout_marginTop="26dp"
android:text="@string/itemQuantity"
android:textColor="@color/white"
android:textSize="25sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="@+id/txtItemPrice"
app:layout_constraintStart_toEndOf="@+id/txtItemName"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0" />
<!-- To display item price -->
<TextView
android:id="@+id/txtItemPrice"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="26dp"
android:layout_marginEnd="22dp"
android:layout_marginRight="22dp"
android:layout_marginBottom="26dp"
android:text="@string/itemPrice"
android:textColor="@color/white"
android:textSize="25sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="@+id/ibDelete"
app:layout_constraintStart_toEndOf="@+id/txtItemQuantity"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0" />
<ImageButton
android:id="@+id/ibDelete"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="26dp"
android:layout_marginRight="26dp"
android:background="@color/black"
android:src="@drawable/ic_action_delete"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="@+id/txtItemPrice"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.257" />
<!-- To display total cost of grocery items -->
<TextView
android:id="@+id/txtItemTotalCost"
android:layout_width="100dp"
android:layout_height="60dp"
android:background="@drawable/adapter2"
android:padding="8dp"
android:paddingStart="12dp"
android:text="@string/totalCost"
android:textSize="30sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="@+id/txtTotalCostTitle"
app:layout_constraintTop_toTopOf="@+id/txtTotalCostTitle"
app:layout_constraintVertical_bias="0.875" />
<!-- This text view is used to add statement for total cost -->
<TextView
android:id="@+id/txtTotalCostTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="77dp"
android:layout_marginLeft="77dp"
android:layout_marginEnd="149dp"
android:layout_marginRight="149dp"
android:layout_marginBottom="16dp"
android:text="@string/totalCostTitle"
android:textColor="@color/white"
android:textSize="20dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="@+id/txtItemTotalCost"
app:layout_constraintStart_toStartOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Output of XML Code:

We will code adapter class for recycler view. In the Grocery Adapter class, we will add constructor value by storing entities class as a list in list variable and create an instance of the view model. In Grocery Adapter we will override three functions: onCreateViewHolder, getItemCount, and onbindViewHolder, we will also create an inner class called grocery view holder. Go to the app > java > com.example.application-name. Right-click on com.example.application-name go to new and create a new Package called Adapter and then right-click on Adapter package and create a Kotlin file/class name it GroceryAdapter. See the below code.
Kotlin
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageButton
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.ishaanbhela.myapplication.UI.GroceryViewModel
class GroceryAdapter(var list: List<GroceryItems>, private val viewModel: GroceryViewModel) :
RecyclerView.Adapter<GroceryAdapter.GroceryViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): GroceryViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.groceryadapter, parent, false)
return GroceryViewHolder(view)
}
override fun getItemCount(): Int = list.size
override fun onBindViewHolder(holder: GroceryViewHolder, position: Int) {
val currentPosition = list[position]
holder.txtItemName.text = currentPosition.itemName
holder.txtItemPrice.text = "${currentPosition.itemPrice}"
holder.txtItemQuantity.text = "${currentPosition.itemQuantity}"
holder.ibDelete.setOnClickListener {
viewModel.delete(currentPosition)
}
// Show total cost and title only for the last item
if (position == list.size - 1) {
val totalCost = list.sumBy { it.itemPrice }
holder.txtItemTotalCost.visibility = View.VISIBLE
holder.txtTotalCostTitle.visibility = View.VISIBLE
holder.txtItemTotalCost.text = "$totalCost"
} else {
// Hide the total cost and title for non-last items
holder.txtItemTotalCost.visibility = View.GONE
holder.txtTotalCostTitle.visibility = View.GONE
}
}
// Inner class for ViewHolder with findViewById
inner class GroceryViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val txtItemName: TextView = itemView.findViewById(R.id.txtItemName)
val txtItemPrice: TextView = itemView.findViewById(R.id.txtItemPrice)
val txtItemQuantity: TextView = itemView.findViewById(R.id.txtItemQuantity)
val txtItemTotalCost: TextView = itemView.findViewById(R.id.txtItemTotalCost)
val txtTotalCostTitle: TextView = itemView.findViewById(R.id.txtTotalCostTitle)
val ibDelete: ImageButton = itemView.findViewById(R.id.ibDelete)
}
}
Step 7: To enter grocery item, quantity, and price from the user we have to create an interface. To implement this interface we will use DialogBox. First create UI of dialog box. In this dialog box we will add three edit text and two text view. Three edit text to enter grocery item name, quantity and price. Two text view one for save and other for cancel. After clicking the save text all data saved into the database and by clicking on the cancel text dialog box closes. Go to the app > res > layout. Right-click on layout, go to new and then add a Layout Resource File and name it as grocerydialog. See xml code of grocerydialog.xml file.
XML
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="310dp"
android:layout_height="250dp"
android:background="@drawable/rectangle">
<!-- To display title-->
<TextView
android:id="@+id/tvTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:layout_marginEnd="5dp"
android:layout_marginRight="5dp"
android:layout_marginBottom="26dp"
android:text="@string/title"
android:textColor="@color/black"
android:textSize="30dp"
app:layout_constraintBottom_toTopOf="@+id/linearLayout"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<!-- Linear Layout is used to give equal
weight sum to edit text-->
<LinearLayout
android:id="@+id/linearLayout"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginBottom="66dp"
android:weightSum="3"
app:layout_constraintBottom_toTopOf="@+id/tvSave"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/tvTitle">
<!-- Edit Text is used to Enter Grocery
Item Name by user-->
<EditText
android:id="@+id/etItemName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="0dp"
android:layout_weight="1"
android:hint="@string/etItem"
android:textSize="30dp"
app:layout_constraintBottom_toTopOf="@+id/tvCancel"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.069"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.661" />
<!-- Edit Text is used to Enter Grocery
Item Quantity by user-->
<EditText
android:id="@+id/etItemQuantity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="0dp"
android:layout_weight="1"
android:hint="@string/etQuantity"
android:inputType="number"
android:textSize="30dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="@+id/etItemPrice"
app:layout_constraintHorizontal_bias="0.461"
app:layout_constraintStart_toEndOf="@+id/etItemName"
app:layout_constraintTop_toBottomOf="@+id/tvTitle"
app:layout_constraintVertical_bias="0.276" />
<!-- Edit Text is used to Enter Grocery
Item Price by user-->
<EditText
android:id="@+id/etItemPrice"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="0dp"
android:layout_weight="1"
android:hint="@string/etPrice"
android:inputType="number"
android:textSize="30dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.861"
app:layout_constraintStart_toEndOf="@+id/etItemName"
app:layout_constraintTop_toTopOf="parent" />
</LinearLayout>
<!-- Text view is used as save button to save
all details in database by user-->
<TextView
android:id="@+id/tvSave"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginEnd="16dp"
android:layout_marginRight="16dp"
android:layout_marginBottom="14dp"
android:text="@string/save"
android:textColor="@color/black"
android:textSize="20dp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="@+id/tvCancel"
app:layout_constraintTop_toBottomOf="@+id/linearLayout" />
<!-- Text View is used to close dialog box-->
<TextView
android:id="@+id/tvCancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="28dp"
android:layout_marginLeft="28dp"
android:layout_marginEnd="154dp"
android:layout_marginRight="154dp"
android:layout_marginBottom="14dp"
android:text="@string/cancel"
android:textColor="@color/black"
android:textSize="20dp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="@+id/tvSave"
app:layout_constraintStart_toStartOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Output of XML Code:
To add a clicklistener on save text we have to create an interface first in which we create a function. Go to the app > java > com.example.application-name > UI. Right-click on the UI package and create a Kotlin file/class and create an interface name it as DialogListener. See the code of the DialogListener.kt file.
Kotlin
import com.example.grocerylist.Database.Entity.GroceryItems
interface DialogListener {
// Create a function to add items
// in GroceryItems on clicking
fun onAddButtonClicked(item:GroceryItems)
}
Now we will create grocery dialog class in which we save all input in different variable and then insert in database. Go to the app > java > com.example.application-name > UI. Right-click on UI package and create a Kotlin file/class and create an class name it GroceryItemDialog. See the below code.
Kotlin
import android.content.Context
import android.os.Bundle
import android.view.Window
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatDialog
import com.ishaanbhela.myapplication.GroceryItems
import com.ishaanbhela.myapplication.R
class GroceryItemDialog(context: Context, var dialogListener: DialogListener) : AppCompatDialog(context) {
lateinit var etItemName : EditText
lateinit var etItemQuantity : EditText
lateinit var etItemPrice : EditText
lateinit var tvSave : TextView
lateinit var tvCancel : TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
supportRequestWindowFeature(Window.FEATURE_NO_TITLE)
setContentView(R.layout.grocerydialog)
etItemName = findViewById(R.id.etItemName)!!
etItemQuantity = findViewById(R.id.etItemQuantity)!!
etItemPrice = findViewById(R.id.etItemPrice)!!
tvSave = findViewById(R.id.tvSave)!!
tvCancel = findViewById(R.id.tvCancel)!!
// Click listener on Save button
// to save all data.
tvSave.setOnClickListener {
// Take all three inputs in different variables from user
// and add it in Grocery Items database
val name = etItemName.text.toString()
val quantity = etItemQuantity.text.toString().toInt()
val price = etItemPrice.text.toString().toInt()
// Toast to display enter items in edit text
if (name.isEmpty()) {
Toast.makeText(context, "Please Enter Item Name", Toast.LENGTH_SHORT).show()
}
val item = GroceryItems(name, quantity, price)
dialogListener.onAddButtonClicked(item)
dismiss()
}
// On click listener on cancel text to close dialog box
tvCancel.setOnClickListener {
cancel()
}
}
}
Step 8: In this step finally we will code in our MainActivity. In our main activity, we have to set up the recycler view and add click listener on add button to open the dialog box. Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.
Kotlin
import android.os.Bundle
import android.widget.ImageButton
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.room.InvalidationTracker
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.RecyclerView
import com.ishaanbhela.myapplication.UI.DialogListener
import com.ishaanbhela.myapplication.UI.GroceryItemDialog
import com.ishaanbhela.myapplication.UI.GroceryViewModel
import com.ishaanbhela.myapplication.UI.GroceryViewModelFactory
class MainActivity : AppCompatActivity() {
lateinit var ViewModel: GroceryViewModel
lateinit var list: List<GroceryItems>
lateinit var rvList : RecyclerView
lateinit var btnAdd : ImageButton
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContentView(R.layout.activity_main)
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
insets
}
btnAdd = findViewById(R.id.btnAdd)
rvList = findViewById(R.id.rvList)
val groceryRepository = GroceryRepository(GroceryDatabase(this))
val factory = GroceryViewModelFactory(groceryRepository)
// Initialised View Model
ViewModel = ViewModelProvider(this, factory).get(GroceryViewModel::class.java)
val groceryAdapter = GroceryAdapter(listOf(), ViewModel)
rvList.layoutManager = LinearLayoutManager(this)
rvList.adapter = groceryAdapter
// To display all items in recycler view
ViewModel.allGroceryItems().observe(this, Observer {
groceryAdapter.list = it
groceryAdapter.notifyDataSetChanged()
})
// on ClickListener on button to open dialog box
btnAdd.setOnClickListener {
GroceryItemDialog(this, object : DialogListener {
override fun onAddButtonClicked(item: GroceryItems) {
ViewModel.insert(item)
}
}).show()
}
}
}
This is how the complete project structure looks like.

Output:
Github Link: Click Here to Access the whole Project
Similar Reads
Android Tutorial
In this Android Tutorial, we cover both basic and advanced concepts. So whether you are a fresher (graduate) or an experienced candidate with several years of Android Development experience, you can follow this Android tutorial to kick-start your journey in Android app development. Our Android Tutor
15+ min read
Basics
Introduction to Android Development
Android operating system is the largest installed base among various mobile platforms across the globe. Hundreds of millions of mobile devices are powered by Android in more than 190 countries of the world. It conquered around 71% of the global market share by the end of 2021, and this trend is grow
5 min read
History of Android
Android devices form a very essential part of a huge section of mobile phone users in today's world. With the global turmoil in the COVID-19 eras, the population has now entered a digital sphere. Android is the most used OS in smartphones during these days of transformation. But when did something l
15+ min read
Best Way to Become Android Developer â A Complete Roadmap
Android is an open-source operating system, based on the Linux kernel and used in mobile devices like smartphones, tablets, etc. Further, it was developed for smartwatches and Android TV. Each of them has a specialized interface. Android has been one of the best-selling OS for smartphones. Android O
7 min read
Android Development Prerequisites [2025] - Things to Learn Before Android Development
Have you ever wondered how your phone's appsâsuch as those for making calls, playing games, or checking the weatherâare created? Android Development is the procedure used to generate these apps. The Android operating system powers the majority of phones, just like an engine powers a car. To ensure t
8 min read
Android App Development Fundamentals for Beginners
Android is an operating system that is built basically for Mobile phones. It is based on the Linux Kernel and other open-source software and is developed by Google. It is used for touchscreen mobile devices such as smartphones and tablets. But nowadays these are used in Android Auto cars, TV, watche
6 min read
Android Architecture
Android architecture contains a different number of components to support any Android device's needs. Android software contains an open-source Linux Kernel having a collection of a number of C/C++ libraries which are exposed through application framework services. Among all the components Linux Kern
5 min read
Android System Architecture
The Android software stack generally consists of a Linux kernel and a collection of C/C++ libraries that are exposed through an application framework that provides services, and management of the applications and run time. Linux KernelAndroid was created on the open-source kernel of Linux. One main
3 min read
Android Boot Process
Booting Process In computing, booting is starting up a computer or computer appliance until it can be used. It can be initiated by hardware such as a button press, or by software command. After the power is switched on the computer is relatively dumb, and can read only part of its storage called Rea
4 min read
Difference between Java and Kotlin in Android with Examples
Kotlin KOTLIN is a cross platform, statically types, general purpose programming language with type inference. KOTLIN is designed to interoperate fully with java but type inference allows its syntax to be more concise.KOTLIN is sponsored by JetBrains and Google through the Kotlin Foundation. Java JA
3 min read
Interesting Facts About Android
Android is a Mobile Operating System that was released on 23, September 2008. Android is free, open-source operating system and is based on modified version of Linux kernel. Open Handset Alliance (OHA) developed the Android and Google commercially sponsored it. It is mainly designed for touchscreen
3 min read
Software Setup and Configuration
Android Studio Tutorial
It is stated that "If you give me six hours to chop down a tree then I will spend the first four hours in sharpening the axe". So in the Android Development World if we consider Android Development as the tree then Android Studio should be the axe. Yes, if you are starting Android Development then y
9 min read
File Structure & Components
Core Topics
How Does Android App Work?
Developing an android application involves several processes that happen in a sequential manner. After writing the source code files, when developers click the Run button on the Android studio, plenty of operations and process starts at the backend. Every operation happening in the background is a c
7 min read
Activity Lifecycle in Android with Demo App
In Android, an activity is referred to as one screen in an application. It is very similar to a single window of any desktop application. An Android app consists of one or more screens or activities. Each activity goes through various stages or a lifecycle and is managed by activity stacks. So when
9 min read
Introduction to Gradle
Gradle is an excellent open-source construction tool that is capable of the development of any kind of software. This tool was developed by a gaggle of developers named Hans Dockter, Szczepan Faber Adam Murdoch, Luke Daley, Peter Niederwieser, Daz DeBoer, and Rene Gröschkebefore 13 years before. It
8 min read
What is Context in Android?
Android Applications are popular for a long time and it is evolving to a greater level as users' expectations are that they need to view the data that they want in an easier smoother view. Hence, the android developers must know the important terminologies before developing the app. In Android Progr
9 min read
Bundle in Android with Example
It is known that Intents are used in Android to pass to the data from one activity to another. But there is one another way, that can be used to pass the data from one activity to another in a better way and less code space ie by using Bundles in Android. Android Bundles are generally used for passi
6 min read
Activity State Changes In Android with Example
Prerequisites: Activity lifecycle in android As it is known that every Android app has at least one activity associated with it. When the application begins to execute and runs, there are various state changes that activity goes through. Different events some user-triggered and some system triggered
6 min read
Processes and Application Lifecycle in Android
As an android developer, if one does not know the application lifecycle of android application or does not have in-depth knowledge about it, there are very high chances that the application will not have a good user experience. Not having proper knowledge of the application lifecycle will not affect
7 min read
Desugaring in Android
Google has officially announced Kotlin as a recommended language for Android Development and that's why so many developers are switching from Java to Kotlin for Android development. So day by day new APIs are been introduced in Android by the Google Team and which are available in newer versions of
4 min read
Difference Between AndroidX and Android Support Libraries
Support library packages in Android are a set of code libraries whose prime purpose is to provide backward-compatibility to the code and Android API framework. In the real world, there is a strong possibility that an application that is developed on the latest Android version is used on an older ver
3 min read
Memory Leaks in Android
A memory leak is basically a failure of releasing unused objects from the memory. As a developer one does not need to think about memory allocation, memory deallocation, and garbage collection. All of these are the automatic process that the garbage collector does by itself, but the situation become
7 min read
Layout & View
Layouts in Android UI Design
Layout Managers (or simply layouts) are said to be extensions of the ViewGroup class. They are used to set the position of child Views within the UI we are building. We can nest the layouts, and therefore we can create arbitrarily complex UIs using a combination of layouts. There is a number of layo
2 min read
Android UI Layouts
Layouts in Android is used to define the user interface that holds the UI controls or widgets that will appear on the screen of an android application or activity screen. Generally, every application is a combination of View and ViewGroup. As we know, an android application contains a large number o
5 min read
LinearLayout and its Important Attributes with Examples in Android
LinearLayout is one of the most basic layouts in android studio, that arranges multiple sub-views (UI elements) sequentially in a single direction i.e. horizontal or vertical manner by specifying the android:orientation attribute. If one applies android:orientation="vertical" then elements will be a
3 min read
Android LinearLayout in Kotlin
LinearLayout in Android is a ViewGroup subclass, used to arrange child view elements one by one in a singular direction either horizontally or vertically based on the orientation attribute. We can specify the linear layout orientation using the android:orientation attribute. All the child elements a
2 min read
Android RelativeLayout in Kotlin
RelativeLayout in Android is a ViewGroup subclass, that allows users to position child views relative to each other (e.g., view A to the right of view B) or relative to the parent (e.g., aligned to the top of the parent). Instead of using LinearLayout, we have to use RelativeLayout to design the use
4 min read
ConstraintLayout in Android
ConstraintLayout is the most advanced layout in Android that lets you create complex and responsive UIs while minimizing nested views due to its flat view hierarchy. ConstraintLayout is similar to that of other View Groups which we have seen in Android such as RelativeLayout, LinearLayout, and many
6 min read
TextView widget in Android with Examples
Widget refers to the elements of the UI (User Interface) that help the user interact with the Android App. TextView is one of many such widgets which can be used to improve the UI of the app. TextView refers to the widget which displays some text on the screen based on the layout, size, colour, etc
5 min read
TextView in Kotlin
Android TextView is simply a view that are used to display the text to the user and optionally allow us to modify or edit it. First of all, open Kotlin project in Android Studio. Following steps are used to create Steps to Implement TextViewSteps by Step implementation for creating an application wh
3 min read
Working With the TextView in Android
TextView in Android is one of the basic and important UI elements. This plays a very important role in the UI experience and depends on how the information is displayed to the user. This TextView widget in Android can be dynamized in various contexts. For example, if the important part of the inform
7 min read
Autosizing TextView in Android
If the user is giving the input and the input needs to be shown as TextView and if the user inputs the stuff which can go out of the screen, then in this case the font TextView should be decreased gradually. So, in this article, it has been discussed how the developer can reduce the size of TextView
6 min read
Intent and Intent Filters
What is Intent in Android?
In Android, it is quite usual for users to witness a jump from one application to another as a part of the whole process, for example, searching for a location on the browser and witnessing a direct jump into Google Maps or receiving payment links in Messages Application (SMS) and on clicking jumpin
4 min read
Implicit and Explicit Intents in Android with Examples
Pre-requisites: Android App Development Fundamentals for Beginners Guide to Install and Set up Android Studio Android | Starting with the first app/android project Android | Running your first Android app This article aims to tell about the Implicit and Explicit intents and how to use them in an and
7 min read
How to Send Data From One Activity to Second Activity in Android?
This article aims to tell and show how to "Send the data from one activity to second activity using Intent" . In this example, we have two activities, activity_first which are the source activity, and activity_second which is the destination activity. We can send the data using the putExtra() method
7 min read
How to open dialer in Android through Intent?
The phone dialer is an activity available with the Android operating system to call a number. Usually, such activity may or may not have an EditText, for taking the number as input, and a Call button. When the user presses the Call button, it invokes the dialer app activity. Use of 'tel:' prefix is
3 min read
Creating Multiple Screen Applications in Android
This article shows how to create an android application to move from one activity to another using the concept of Explicit Intents. Below are the steps for Creating a Simple Android Application to move from one activity to another activity. Step By Step ImplementationStep 1: Create a New Project in
6 min read
How to Open Camera Through Intent and Display Captured Image in Android?
Pre-requisites: Android App Development Fundamentals for Beginners Guide to Install and Set up Android Studio Android | Starting with first app/android project Android | Running your first Android app The purpose of this article is to show how to open a Camera from inside an App and click the image
5 min read
Toast & RecyclerView
Toasts for Android Studio
A toast provides a simple popup message that is displayed on the current activity UI screen (e.g. Main Activity). Example: Syntax: // To get ContextContext context = getApplicationContext(); // Message to displayString text = "Toast message"; // Toast time duration, can also set manual value int dur
2 min read
What is Toast and How to Use it in Android with Examples?
Pre-requisites: Android App Development Fundamentals for BeginnersGuide to Install and Set up Android StudioAndroid | Starting with the first app/android projectAndroid | Running your first Android appWhat is Toast in Android? A Toast is a feedback message. It takes a very little space for displayin
6 min read
Android Toast in Kotlin
A Toast is a short alert message shown on the Android screen for a short interval of time. Android Toast is a short popup notification which is used to display information when we perform any operation in our app. In this tutorial, we shall not just limit ourselves by creating a lame toast but also
4 min read
How to Change Toast font in Android?
A Toast is a feedback message. It takes a very little space for displaying while overall activity is interactive and visible to the user. It disappears after a few seconds. It disappears automatically. If user wants permanent visible message, Notification can be used. Note: Toast disappears automati
3 min read
How to add a custom styled Toast in Android
A Toast is a feedback message. It takes very little space for displaying and it is displayed on top of the main content of an activity, and only remains visible for a short time period. This article explains how to create Custom Toast messages, which has custom background, image, icon, etc, which ar
4 min read
RecyclerView in Android with Example
RecyclerView is a ViewGroup added to the android studio as a successor of the GridView and ListView. It is an improvement on both of them and can be found in the latest v-7 support packages. It has been created to make possible construction of any lists with XML layouts as an item which can be custo
7 min read
Android | Horizontal RecyclerView with Examples
Recycler View is a ViewGroup added to Android Studio as a successor of the GridView and ListView. It is an improvement on both of them and can be found in the latest v-7 support packages. It has been created to make possible construction of any lists with XML layouts as an item which can be customiz
4 min read
How to create a nested RecyclerView in Android
A nested RecyclerView is an implementation of a RecyclerView within a RecyclerView. An example of such a layout can be seen in a variety of apps such as the Play Store, where the outer (parent) RecyclerView is of vertical orientation, whereas the inner (child) RecyclerViews are of horizontal orienta
6 min read
How to Create RecyclerView with Multiple ViewType in Android?
RecyclerView forms a crucial part of the UI in Android app development. It is especially important to optimize memory consumption when displaying a long list of items. A RecyclerView inflates a customized list of items, which can have either similar layouts or multiple distinct layouts. Here, we dev
6 min read
RecyclerView using ListView in Android With Example
RecyclerView is a more flexible and advanced version of ListView and GridView. RecyclerView is used for providing a limited window to a large data set, which means it is used to display a large amount of data that can be scrolled very efficiently by maintaining a limited number of Views. In Recycler
6 min read