Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Getting Started with Room Persistence Library

Getting Started with Room Persistence Library

This Talk presents a Fundamental of Room Persistence Library in Android Application Devlopement by Soham Pandya

More Decks by Technophile Community Surat

Other Decks in Programming

Transcript

  1. Room Persistence Library • The Room persistence library provides an

    abstraction layer over SQLite to allow fluent database access while harnessing the full power of SQLite.
  2. • Boilerplate code • No direct object mapping • Difficult

    to implement database migration • Difficult to test • Database operation on main thread Drawbacks of SQLite Database
  3. Entity • Represents a table within the database. • @Entity(tableName

    = "users") • Annotations – ColumnInfo, PrimaryKey, Ignore, Index, Embedded •https://developer.android.com/reference/android/arch /persistence/room/package-summary.html
  4. Entity ▶ @Entity (tablename = “user”) public class User {

    @PrimaryKey(autoGenerate = true) private int uid; @ColumnInfo(name = "first_name") private String firstName; @ColumnInfo(name = "last_name") private String lastName; // Getters and setters are ignored for brevity, // but they're required for Room to work. }
  5. Data Access Object • DAOs are responsible for defining the

    methods that access the database. • @Dao : Marks the class as a Data Access Object. • @Insert , @Delete , @Query , @RawQuery ,@Update
  6. Data Access Object ▶ User.java ▶ @Dao public interface UserDao

    { @Query("SELECT * FROM user") List<User> getAll(); @Query("SELECT * FROM user WHERE uid IN (:userIds)") List<User> loadAllByIds(int[] userIds); ▶ @Query("SELECT * FROM user WHERE uid IN (:userIds)") LiveData<List<User>> loadAllByIds(int[] userIds); ……
  7. Data Access Object ▶ …… ▶ @Query("SELECT * FROM user

    WHERE first_name LIKE :first AND last_name LIKE :last LIMIT 1") User findByName(String first, String last); @Insert void insertAll(User... users); @Delete void delete(User user); ▶ @Update int update(User user); }
  8. Database • The main access point to your app's persisted,

    relational data. • The class that's annotated with @Database should satisfy the following conditions: • Abstract class that extends RoomDatabase. • Include the list of entities associated with the database within the annotation. • Contain an abstract method that has 0 arguments and returns the class that is annotated with @Dao.
  9. Database ▶ @Database(entities = {User.class}, version = 1) ▶ public

    abstract class AppDatabase extends RoomDatabase { ▶ public abstract UserDao userDao(); ▶} AppDatabase.java
  10. Keep in mind you must call it in a separate

    thread • java.lang.IllegalStateException ▶ Cannot access database on the main thread since it may potentially lock the UI for long period of time. • to allow queries on the main thread. Don't do this on a real app! • MyApp.database = Room.databaseBuilder(context.getApplicationContext(), AppDatabase.class, "user-database") .allowMainThreadQueries() .build();
  11. Migration • java.lang.IllegalStateException • Room cannot verify the data integrity.

    Looks like you’ve changed schema but forgot to update the version number. You can simply fix this by increasing the version number. • A migration from 1 to 2 is necessary. Please provide a Migration in the builder or call fallbackToDestructiveMigration in the builder in which case Room will re-create all of the tables. • Two Solutions : 1) Drop and recreate the whole database. 2) Upgrade existing database schema to the newer version.
  12. Migration • Drop and recreate the whole database ▶ Room.databaseBuilder(context,

    RepoDatabase.class, DB_NAME) .fallbackToDestructiveMigration() .build(); • Allows Room to destructively recreate database tables if Migrations that would migrate old database schemas to the latest schema version are not found. • Note that this will delete all of the data in the database tables managed by Room.
  13. Migration • Migration FROM_1_TO_2 ▶ Room.databaseBuilder(context, RepoDatabase.class, DB_NAME) .addMigrations(FROM_1_TO_2) .build();

    • static final Migration FROM_1_TO_2 = new Migration(1, 2) • { @Override public void migrate(final SupportSQLiteDatabase database) • { • database.execSQL("ALTER TABLE Repo ADD COLUMN createdAt TEXT"); • } };
  14. What we get ? • Easier than using SQLite directly.

    • It makes you verify your database code during compile time. • It makes your code more modular and readable as you divide your database code in three components like Entity ,DAO and Database.
  15. • Architecture Components: Room (https://www.youtube.com/watch?v=H7I3zs-L-1w) • Room Database Guides (https://developer.android.com/training/data-storage/room/index.html)

    • Persisting Data with Room on Android - Orlando Android (https://www.youtube.com/watch?v=9xdtVdO-XAA) • Medium : SQLite Made Easy : Room Persistence Library ▶ (https://medium.com/mindorks/sqlite-made-easy-room-persistence-library-ecd1a5bb0a2c) References