- 14.1B: Deleting and updating data with Room
- What you should already KNOW
- What you will LEARN
- What you will DO
- App overview
- Task 1. Initialize data only if the database is empty
- 1.1 Add a method to the DAO to get a single word
- 1.2 Update the initialization method to check whether data exists
- Task 2. Delete all words
- 2.1 Add deleteAll() to the WordDao interface and annotate it
- 2.2 Add deleteAll() to the WordRepository class
- 2.3 Add deleteAll() to the WordViewModel class
- Task 3. Add an Options menu item to delete all data
- 3.1 Add the Clear all data menu option
- Task 4. Delete a single word
- 4.1 Add deleteWord() to the DAO and annotate it
- 4.2 Add deleteWord() to the WordRepository class
- 4.3 Add deleteWord() to the WordViewModel class
- Task 5. Enable users to swipe words away
- 5.1 Enable the adapter to detect the swiped word
- Solution code
- Coding challenge
- Hints
- Challenge solution code
- Summary
- Writing database code
- ItemTouchHelper
- Related concept
- Learn more
- 7 Pro-tips for Room
- 7 Steps To Room
- A step by step guide on how to migrate your app to Room
- 1. Pre-populate the database
- 2. Use DAO’s inheritance capability
- 3. Execute queries in transactions with minimal boilerplate code
- 4. Read only what you need
- 5. Enforce constraints between entities with foreign keys
- 6. Simplify one-to-many queries via @Relation
- 7. Avoid false positive notifications for observable queries
14.1B: Deleting and updating data with Room
Contents:
This practical gives you more practice at using the API provided by the Room library to implement database functionality. You will add the ability to delete specific items from the database. The practical also includes a coding challenge, in which you update the app so the user can edit existing data.
What you should already KNOW
You should be able to create and run apps in Android Studio 3.0 or higher. In particular, be familiar with the following:
- Using RecyclerView and adapters.
- Using entity classes, data access objects (DAOs), and the RoomDatabase to store and retrieve data in Android’s built-in SQLite database. You learned these topics in the previous practical, 15.1A: Working with Architecture Components: Room, LiveData, ViewModel.
What you will LEARN
You will learn how to:
- Populate the database with data only if the database is empty (so users don’t lose changes they made to the data).
- Delete data from a Room database.
- Update existing data (if you build the challenge app).
What you will DO
- Update the RoomWordsSample app to keep data when the app closes.
- Allow users to delete all words by selecting an Options menu item.
- Allow users to delete a specific word by swiping an item in the list.
- Optionally, in a coding challenge, extend the app to allow the user to update existing words.
App overview
You will extend the RoomWordsSample app that you created in the previous practical. So far, that app displays a list of words, and users can add words. When the app closes and re-opens, the app re-initializes the database, and words that the user has added are lost.
In this practical, you extend the app so that it only initializes the data in the database if there is no existing data.
Then you add a menu item that allows the user to delete all the data.
You also enable the user to swipe a word to delete it from the database.
Task 1. Initialize data only if the database is empty
The RoomWordsSample app that you created in the previous practical deletes and re-creates the data whenever the user opens the app. This behavior isn’t ideal, because users will want their added words to remain in the database when the app is closed.
In this task you update the app so that when it opens, the initial data set is only added if the database has no data.
To detect whether the database contains data already, you can run a query to get one data item. If the query returns nothing, then the database is empty.
1.1 Add a method to the DAO to get a single word
Currently, the WordDao interface has a method for getting all the words, but not for getting any single word. The method to get a single word does not need to return LiveData , because your app will call the method explicitly when needed.
- In the WordDao interface, add a method to get any word: Room issues the database query when the getAnyWord() method is called and returns an array containing one word. You don’t need to write any additional code to implement it.
1.2 Update the initialization method to check whether data exists
Use the getAnyWord() method in the method that initializes the database. If there is any data, leave the data as it is. If there is no data, add the initial data set.
PopulateDBAsync is an inner class in WordRoomDatbase . In PopulateDBAsync , update the doInBackground() method to check whether the database has any words before initializing the data:
Task 2. Delete all words
In the previous practical, you used the deleteAll() method to clear out all the data when the database opened. The deleteAll() method was only invoked from the PopulateDbAsync class when the app started. Make the deleteAll() method available through the ViewModel so that your app can call the method whenever it’s needed.
Here are the general steps for implementing a method to use the Room library to interact with the database:
- Add the method to the DAO, and annotate it with the relevant database operation. For the deleteAll() method, you already did this step in the previous practical.
- Add the method to the WordRepository class. Write the code to run the method in the background.
- To call the method in the WordRepository class, add the method to the WordViewModel . The rest of the app can then access the method through the WordViewModel .
2.1 Add deleteAll() to the WordDao interface and annotate it
- In WordDao , check that the deleteAll() method is defined and annotated with the SQL that runs when the method executes:
2.2 Add deleteAll() to the WordRepository class
Add the deleteAll() method to the WordRepository and implement an AsyncTask to delete all words in the background.
In WordRepository , define deleteAllWordsAsyncTask as an inner class. Implement doInBackground() to delete all the words by calling deleteAll() on the DAO:
2.3 Add deleteAll() to the WordViewModel class
You need to make the deleteAll() method available to the MainActivity by adding it to the WordViewModel .
- In the WordViewModel class, add the deleteAll() method:
Task 3. Add an Options menu item to delete all data
Next, you will add a menu item to enable users to invoke deleteAll() .
3.1 Add the Clear all data menu option
- In menu_main.xml , change the menu option title and id , as follows:
In MainActivity , implement the onOptionsItemSelected() method to invoke the deleteAll() method on the WordViewModel object.
Task 4. Delete a single word
Your app lets users add words and delete all words. In Tasks 4 and 5, you extend the app so that users can delete a word by swiping the item in the RecyclerView .
Again, here are the general steps to implement a method to use the Room library to interact with the database:
- Add the method to the DAO, and annotate it with the relevant database operation.
- Add the method to the WordRepository class. Write the code to run the method in the background.
- To call the method in the WordRepository class, add the method to the WordViewModel . The rest of the app can then access the method through the WordViewModel .
4.1 Add deleteWord() to the DAO and annotate it
- In WordDao , add the deleteWord() method:Because this operation deletes a single row, the @Delete annotation is all that is needed to delete the word from the database.
4.2 Add deleteWord() to the WordRepository class
In WordRepository , define another AsyncTask called deleteWordAsyncTask as an inner class. Implement doInBackground() to delete a word bycalling deleteWord() on the DAO:
4.3 Add deleteWord() to the WordViewModel class
To make the deleteWord() method available to other classes in the app, in particular, MainActivity, add it to WordViewModel .
- In WordViewModel , add the deleteWord() method:You have now implemented the logic to delete a word, but as yet there is no way to invoke the delete-word operation from the app’s UI. You fix that next.
Task 5. Enable users to swipe words away
In this task, you add functionality to allow users to swipe an item in the RecyclerView to delete it.
Use the ItemTouchHelper class provided by the Android Support Library (version 7 and higher) to implement swipe functionality in your RecyclerView . The ItemTouchHelper class has the following methods:
- onMove() is called when the user moves the item. You do not implement any move functionality in this app.
- onSwipe() is called when the user swipes the item. You implement this method to delete the word that was swiped.
5.1 Enable the adapter to detect the swiped word
- In WordListAdapter , add a method to get the word at a given position.
In MainActivity , in onCreate() , create the ItemTouchHelper . Attach the ItemTouchHelper to the RecyclerView .
Things to notice in the code:
onSwiped() gets the position of the ViewHolder that was swiped:
Given the position, you can get the word displayed by the ViewHolder by calling the getWordAtPosition() method that you defined in the adapter:
Delete the word by calling deleteWord() on the WordViewModel :
Now run your app and delete some words
- Run your app. You should be able to delete words by swiping them left or right.
Solution code
Coding challenge
Challenge: Update your app to allow users to edit a word by tapping the word and then saving their changes.
Hints
Make changes in NewWordActivity
You can add functionality to NewWordActivity , so that it can be used either to add a new word or edit an existing word.
Use an auto-generated key in Word
The Word entity class uses the word field as the database key. However, when you update a row in the database, the item being updated cannot be the primary key, because the primary key is unique to each row and never changes. So you need to add an auto-generated id to use as the primary key
Add a constructor for Word that takes an id
Add a constructor to the Word entity class that takes id and word as parameters. Make sure this additional constructor is annotated using @Ignore , because Room expects only one constructor by default in an entity class.
To update an existing Word , create the Word using this constructor. Room will use the primary key (in this case the id ) to find the existing entry in the database so it can be updated.
In WordDao , add the update() method like this:
Challenge solution code
Android Studio project: Coming soon
Summary
Writing database code
- Room takes care of opening and closing the database connections each time a database operations executes.
- Annotate methods in the data access object (DAO) as @insert , @delete , @update , @query .
- For simple insertions, updates and deletions, it is enough to add the relevant annotation to the method in the DAO.
- For queries or more complex database interactions, such as deleting all words, use the @query annotation and provide the SQL for the operation.
ItemTouchHelper
- To enable users to swipe or move items in a RecyclerView , you can use the ItemTouchHelper class.
- Implement onMove() and onSwipe().
- To identify which item the user moved or swiped, you can add a method to the adapter for the RecylerView . The method takes a position and returns the relevant item. Call the method inside onMove() or onSwipe() .
Related concept
The related concept documentation is Architecture Components.
Learn more
Entities, data access objects (DAOs), and ViewModel :
- Defining data using Room entities
- Accessing data using Room DAOs
- ViewModel guide
- Dao reference
- ViewModel reference
- To see all the possible annotations for an entity, go to android.arch.persistence.room in the Android reference and expand the Annotations menu item in the left nav.
Источник
7 Pro-tips for Room
Room is an abstraction layer on top of SQLite that makes it easier and nicer to persist data. If you’re new to Room then check out this primer:
7 Steps To Room
A step by step guide on how to migrate your app to Room
In this article, I’d like to share some pro-tips on getting the most out of Room:
1. Pre-populate the database
Do you need to add default data to your database, right after it was created or when the database is opened? Use RoomDatabase#Callback ! Call the addCallback method when building your RoomDatabase and override either onCreate or onOpen .
onCreate will be called when the database is created for the first time, after the tables have been created. onOpen is called when the database was opened. Since the DAOs can only be accessed once these methods return, we‘re creating a new thread where we’re getting a reference to the database, get the DAO, and then insert the data.
See a full example here.
Note: When using the ioThread approach, if your app crashes at the first launch, in between database creation and insert, the data will never be inserted.
2. Use DAO’s inheritance capability
Do you have multiple tables in your database and find yourself copying the same Insert , Update and Delete methods? DAOs support inheritance, so create a BaseDao class, and define your generic @Insert , @Update and @Delete methods there. Have each DAO extend the BaseDao and add methods specific to each of them.
See more details here.
The DAOs have to be interfaces or abstract classes because Room generates their implementation at compile time, including the methods from BaseDao .
3. Execute queries in transactions with minimal boilerplate code
Annotating a method with @Transaction makes sure that all database operations you’re executing in that method will be run inside one transaction. The transaction will fail when an exception is thrown in the method body.
You might want to use the @Transaction annotation for @Query methods that have a select statement, in the following cases:
- When the result of the query is fairly big. By querying the database in one transaction, you ensure that if the query result doesn’t fit in a single cursor window, it doesn’t get corrupted due to changes in the database between cursor window swaps.
- When the result of the query is a POJO with @Relation fields. The fields are queries separately so running them in a single transaction will guarantee consistent results between queries.
@Delete , @Update and @Insert methods that have multiple parameters are automatically run inside a transaction.
4. Read only what you need
When you’re querying the database, do you use all the fields you return in your query? Take care of the amount of memory used by your app and load only the subset of fields you will end up using. This will also improve the speed of your queries by reducing the IO cost. Room will do the mapping between the columns and the object for you.
Consider this complex User object:
On some screens we don’t need to display all of this information. So instead, we can create a UserMinimal object that holds only the data needed.
In the DAO class, we define the query and select the right columns from the users table.
5. Enforce constraints between entities with foreign keys
Even though Room doesn’t directly support relations, it allows you to define Foreign Key constraints between entities.
Room has the @ForeignKey annotation, part of the @Entity annotation, to allow using the SQLite foreign key features. It enforces constraints across tables that ensure the relationship is valid when you modify the database. On an entity, define the parent entity to reference, the columns in it and the columns in the current entity.
Consider a User and a Pet class. The Pet has an owner, which is a user id referenced as foreign key.
Optionally, you can define what action to be taken when the parent entity is deleted or updated in the database. You can choose one of the following: NO_ACTION , RESTRICT , SET_NULL , SET_DEFAULT or CASCADE , that have same behaviors as in SQLite.
Note: In Room, SET_DEFAULT works as SET_NULL , as Room does not yet allow setting default values for columns.
6. Simplify one-to-many queries via @Relation
In the previous User — Pet example, we can say that we have a one-to-many relation: a user can have multiple pets. Let’s say that we want to get a list of users with their pets: List .
To do this manually, we would need to implement 2 queries: one to get the list of all users and another one to get the list of pets based on a user id.
We would then iterate through the list of users and query the Pets table.
To make this simpler, Room’s @Relation annotation automatically fetches related entities. @Relation can only be applied to a List or Set of objects. The UserAndAllPets class has to be updated:
In the DAO, we define a single query and Room will query both the Users and the Pets tables and handle the object mapping.
7. Avoid false positive notifications for observable queries
Let’s say that you want to get a user based on the user id in an observable query:
You’ll get a new emission of the User object whenever that user updates. But you will also get the same object when other changes (deletes, updates or inserts) occur on the Users table that have nothing to do with the User you’re interested in, resulting in false positive notifications. Even more, if your query involves multiple tables, you’ll get a new emission whenever something changed in any of them.
Here’s what’s going on behind the scenes:
- SQLite supports triggers that fire whenever a DELETE , UPDATE or INSERT happens in a table.
- Room creates an InvalidationTracker that uses Observers that track whenever something has changed in the observed tables.
- Both LiveData and Flowable queries rely on the )» target=»_blank» rel=»noopener ugc nofollow»>InvalidationTracker.Observer#onInvalidated notification. When this is received, it triggers a re-query.
Room only knows that the table has been modified but doesn’t know why and what has changed. Therefore, after the re-query, the result of the query is emitted by the LiveData or Flowable . Since Room doesn’t hold any data in memory and can’t assume that objects have equals() , it can’t tell whether this is the same data or not.
You need to make sure that your DAO filters emissions and only reacts to distinct objects.
If the observable query is implemented using Flowables , use Flowable#distinctUntilChanged .
If your query returns a LiveData , you can use a MediatorLiveData that only allows distinct object emissions from a source.
In your DAOs, make method that returns the distinct LiveData public and the method that queries the database protected .
See more of the code here.
Note: if you’re returning a list to be displayed, consider using the Paging Library and returning a LivePagedListBuilder since the library will help with automatically computing the diff between list items and updating your UI.
New to Room? Check out our previous articles:
Источник