Recipes App with Local Storage
In this lab, we will be modifying a base project which you can download here.
The project has 3 activities:
- MainActivity - displaying list of recipe titles in a RecyclerView, using a custom RecipesAdapter
- NewRecipeActivity - a set of EditTexts for creating a new recipe
- RecipeDetailsActivity - for showing full details of a recipe
Additionally, the project has:
- RecipeViewModel, which extends AndroidViewModel, a ViewModel variant that also can hold application context.
- It currently holds some placeholder values in its Array
- RecipesAdapter, that pulls data from a RecipeViewModel's recipeArray property . This adapter is used in MainActivity.
- room.RecipeEntity - an empty placeholder class for Recipes
Currently, the application is lacking in features and doesn't do much interesting. Your task is to update the app so that recipes are stored to and loaded from a Room DB.
0. Room dependencies and annotation processing tools
To use Room, you need to add the following to module-level build.gradle:
- At the start of file:
apply plugin: 'kotlin-kapt'
- Inside dependencies { .. } :
implementation 'androidx.room:room-runtime:2.2.5'
kapt 'androidx.room:room-compiler:2.2.5'
1. Set up Room objects: Entity, DAO, and Database
1.1 Entity
Modify the existing RecipeEntity class in package room of the project to make it a proper Room Entity.
- Use the
@Entity
annotation on the class, the class should also be a Kotlin data class instead of a normal class. With data class, you can declare all fields within the constructor, meaning we don't need to write any code within the class body (within the curly braces ). - Add the following fields:
- id - type Int, with annotation
@PrimaryKey(autoGenerate = true)
- title, content, author - of type String?
- preparationTime of type Int?
- id - type Int, with annotation
- Manually set the table name to be 'recipe', by changing the @Entity annotation so that includes argument @Entity(tableName = "recipe")
After modifying the Entitiy, the original code in ViewModel will no longer work due to the signature changing. You can replace the value of recipeArray with an empty array (arrayOf() with no arguments).
1.2 Data Access Object
- Create a new interface, called RecipeDao, the empty class should look like
@Dao interface RecipeDao { }
- Let's add one query to the Dao - to fetch all recipe titles:
@Query("SELECT title FROM recipe") fun loadRecipeTitles(): Array<String>
- Add a 2nd query for inserting recipes:
@Insert(onConflict = OnConflictStrategy.REPLACE) fun insertRecipes(vararg recipes: RecipeEntity)
1.3 Database
- Finally, create the database abstract class, LocalRecipeDb.kt :
@Database(entities = [ ..... ], version = 1) abstract class LocalRecipeDb : RoomDatabase() { abstract fun getRecipesDao(): RecipeDao }
- The array elements for entities should correspond to classes of the Entities you have defined, in our case, it's only RecipeEntity (use
<<Myclassname>>
::class) ).
Now we should have our database established. Note: Whenever you modify the Entity schema after a database exists on the device, you have to update your database version in the RoomDatabase subclass.
- Let's test the database in MainActivity.onCreate():
val db = Room.databaseBuilder( applicationContext, LocalRecipeDb::class.java, "myRecipes") .fallbackToDestructiveMigration() // each time schema changes, data is lost! .allowMainThreadQueries() // if possible, use background thread instead .build()
- Now create a RecipeEntity object instance: and
val newRecipe = RecipeEntity(0, //0 correspond to 'no value', autogenerate handles it for us "Peeled banana", "Take a banana and peel it.", "John", 1)
- Try to insert the entity to the DB using the insert method provided by our DAO:
db.getRecipesDao().<<someMethodHere>>
- To verify that the insert worked, add code after the insert which fetches all the recipe titles from the DB and see if you can log their contents.
2. Using the database from multiple Activities
Since we want to access the database from multiple activities and calling Room's database builder is expensive, we want to avoid re-calling that build procedure multiple times in different activities. We will use the singleton pattern - we create an object of which there can only be a single instance. In Kotlin, this can be done using object declaration. When some component first calls the object, it is initialized. When subsequent components call it, the existing instance is re-used.
We will build the database object inside the companion object of our Room DB class and access it through a method getInstance( .. ) which avoids rebuilding the DB object each time.
- Modify your LocalRecipeDb class, adding the following:
companion object { private lateinit var recipeDb : LocalRecipeDb @Synchronized fun getInstance(context: Context) : LocalRecipeDb { if (!this::recipeDb.isInitialized) { //TODO: build the database } return recipeDb } }
- The above code allows us to call LocalRecipeDb.getInstance(context) from anywhere, returning the singleton instance of the DB.
- Move the DB building code from your MainActivity to the TODO block above, assigning the object it returns to recipeDb, which the method returns.
Now you should be able to get access to the DB from MainActivity using the singleton instead.
3. Showing a list of recipes from DB
Update RecipeViewModel, so that it has a reference to the database through LocalRecipeDb. We do this using Kotlin init clause, which is run when the class instance is created.
init { localDb = LocalRecipeDb.getInstance(application) }
- Now, fill the refresh() function of RecipeViewModel so that it reads all recipes (not just titles) from the DB and sets the value of recipeArray to the DB result.
- First, you need to add a new query to DAO for getting entire recipes!
- instead of selecting titles, you return all columns (with *) and instead of returning Array<String>, you should be returning Array<RecipeEntity>
- Now, you can use the new DAO method in the refresh() function
- First, you need to add a new query to DAO for getting entire recipes!
- Update the RecipesAdapter to also show recipe author next to title (check single_recipe.xml)
4. Adding new Recipes to DB
- Finish the saveButton click listener in NewRecipeActivity
- get a reference to the DB using the LocalDbClient object
- construct a RecipeEntity object and insert it into the DB using a Dao method
- The for inserting we defined above supports passing a single or multiple Recipes!
Since MainActivity onResume() method calls the ViewModel refresh() method and notifies the adapter, the new recipe should become visible in the main list.
5. Optional Bonus Task: Displaying Recipe details from DB
Try to implement fetching of all details for RecipeDetailsActivity and showing them in the UI. Note that RecipesAdapter sets up the click listener for list items, but the new activity launching logic is defined in MainActivity.