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 recipes 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, update the plugins block by adding:
id 'kotlin-kapt'
- Inside dependencies { .. } :
def room_version = "2.4.3" implementation "androidx.room:room-runtime:$room_version" annotationProcessor "androidx.room:room-compiler:$room_version" // To use Kotlin annotation processing tool (kapt) kapt "androidx.room:room-compiler:$room_version"
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)
- author - of type String?
- contents - of type String?
- createdTime of type Date?
- id - type Int, with annotation
- Manually set the table name to be 'recipes', by changing the @Entity annotation so that includes argument @Entity(tableName = "recipes")
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).
Room can automatically convert primary types like Int, String, Long etc to DB table columns. But for types like Date, we need to specify a Type converter.
- Create a new class for converting Dates to Long like below. We will later tell the room DB to make use of this converter.
class DateTypeConverter { @TypeConverter fun toDate(date: Long) = Date(date) @TypeConverter fun fromDate(date: Date?) = date?.time ?: Calendar.getInstance().timeInMillis }
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 name 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 :
@TypeConverters(DateTypeConverter::class) @Database(entities = [ ..... ], version = 1) abstract class LocalRecipeDb : RoomDatabase() { abstract fun getRecipeDao(): 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) ). - The @TypeConverters annotation tells Room how to handle types which aren't supported by the standard Room library. In this case, DateTypeConverter tells Room how to map a Date object to Long, the latter is a type Room can already handle itself.
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.
- Create a function testDB(), call it from onCreate(), inside testDB(), try the following:
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, for testing, let's create a RecipeEntity object instance: and
val newRecipe = RecipeEntity(0, //0 corresponds to 'no value', autogenerate handles it for us "Sandwich", "....", "....", SimpleDateFormat(RecipeEntity.DATEFORMAT).parse("05/10/2022"))
- 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 (using RecipeDAO) and see if you can log their contents.
- If everything works, comment out testDB() from onCreate, so that it won't be used anymore.
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 companion 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. Because RecipeViewModel has a reference to context from its constructor, we can simply define a new class field:
var localDb = LocalRecipeDb.getInstance(app)
- 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 latin name 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 Dao method 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 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.