Sunday, June 3, 2018

Using Room Data Storage in Android

the database is accessed via an abstract class that is extended from RoomDatabase.
Below code can open the database and give a callback

There are three main components in this

1. Database access
2. Creating an entity
3. Mapping a Java object to SQL query (i.e. as a Dao)
4. Accessing the database via Repository

INSTANCE = Room.databaseBuilder(context.getApplicationContext(),
                            WordRoomDatabase.class, "word_database")
                            // Wipes and rebuilds instead of migrating if no Migration object.
                            // Migration is not part of this codelab.
                            .fallbackToDestructiveMigration()
                            .addCallback(sRoomDatabaseCallback)
                            .build();

 private static RoomDatabase.Callback sRoomDatabaseCallback = new RoomDatabase.Callback(){

        @Override
        public void onOpen (@NonNull SupportSQLiteDatabase db){
            super.onOpen(db);
            // If you want to keep the data through app restarts,
            // comment out the following line.
            new PopulateDbAsync(INSTANCE).execute();
        }
    };

like shown above, once the database is opened, Database is populated to read the contents from it.

Now how do we map a java object to an SQL query? This is done using the annotations. Below is a sample Dao

@Dao marks a class as data access object.


@Dao
public interface WordDao {

    // LiveData is a data holder class that can be observed within a given lifecycle.
    // Always holds/caches latest version of data. Notifies its active observers when the
    // data has changed. Since we are getting all the contents of the database,
    // we are notified whenever any of the database contents have changed.
    @Query("SELECT * from word_table ORDER BY word ASC")
    LiveData> getAlphabetizedWords();

    // We do not need a conflict strategy, because the word is our primary key, and you cannot
    // add two items with the same primary key to the database. If the table has more than one
    // column, you can use @Insert(onConflict = OnConflictStrategy.REPLACE) to update a row.
    @Insert
    void insert(Word word);

    @Query("DELETE FROM word_table")
    void deleteAll();
}


references:
https://developer.android.com/training/data-storage/room/

No comments:

Post a Comment