How to Manage SQLite Databases with Room
Room provides an abstraction layer over SQLite to allow fluent database access while harnessing the full power of SQLite database.
Apps that handle non-trivial amounts of structured data can benefit greatly from persisting that data locally. The most common use case is to cache relevant pieces of data. That way, when the device cannot access the network, the user can still browse that content while they are offline. Any user-initiated content changes are then synced to the server after the device is back online.
Because Room takes care of these concerns for you, i highly recommend using Room instead of SQLite.
There are 3 major components in Room:
1) Database: Contains the database holder and serves as the main access point for the underlying connection to your app’s persisted, relational data.
- The class that’s annotated with
@Database
should satisfy the following conditions:
1. Be an abstract class that extends RoomDatabase
.
2. Include the list of entities associated with the database within the annotation.
3. Contain an abstract method that has 0 arguments and returns the class that is annotated with @Dao
.
At runtime, you can acquire an instance of Database
by calling Room.databaseBuilder()
orRoom.inMemoryDatabaseBuilder()
.
2) Entity: Represents a table within the database.
3) DAO: Contains the methods used for accessing the database.
For a hands-on experience with Room, try the Android Room with a View and Android Persistence codelabs. To browse Room code samples, see the Android Architecture Components samples