); ga('send', 'pageview');

Android Room architecture

Room is the future it is a new thing in architecture components. The architecture components have many tools to make a robust app like live data etc. in this article we will specifically talk about room architecture. Data persistence is an imperative factor in any app. Almost majority of apps use some sort of data persistence for example, facebook stores the user information in a database isnode tables like username, password, posts, friends etc. that data can be accessed by the website as well as the app on various platforms like ioS and android. Room architecture provides a useful easy way to encapsulate sqlite and provides an abstraction layer which makes the tasks for data persistence easier and removes the boilerplate code and utilizes sqlite features to maximum optimal way.

Data stored on local device

Room allows the data to be saved on local device. This allows the user to access data even if they have no internet connection. That data can be synced to an online server also if the need arises. Let’s check the contemporary scenario, in this world many countries like india, pakistan and brazil these asian countries have a huge user base but apparently the internet connectivity is not that good. We need to keep low connectivity and bandwidth in our mind while developing applications. The application should also be able to work offline as well. Room enables this by storing the data on local device and then when there is connectivity available you can connect it and sync with a remote server.

An important message to display when in low wifi connectivity

We see a scenario when the connectivity is low or there is no connectivity a toast message is displayed called low connectivity. The user can only view the message and click ok. We need to be more intuitive and display a call to action for example, display a settings button which will take you to wifi setting where user has options like use a data plan etc. yes there is a problem but what can we do about it. This will improve the user experience and will make less friction in the functionality. Reduce the number of steps it takes to do a task to increase simplicity. Make the app as much user friendly as possible.

Room components

We will discuss room components in subsequent lines.

Entity:

An entity is an annotated class which describes a table in the database.

@Entity(tableName = “Item”,

      indices = {@Index(value = “_name”, unique = true)})

public class Item {

 

  @NonNull

  @PrimaryKey(autoGenerate = true)

  @ColumnInfo(name = “_id”)

  private int ItemID;

 

  @ColumnInfo(name = “_name”)

  private String name;

}

As we can see from the code @Entity annotation declare this class as a table in the database. The name of class is item  then we declare the columns and you can declare the getters and setters. By pressing Alt + insert in android studio. For the item class you can declare many attributes like name, sale price, purchase price and quantity. Each attribute in the class will eventually become a column in the table in the database.

Sqlite database

The data in Room is stored in an Sqlite database. Eventually the data can be synced to the remote server. Room manages the boilerplate code for you to make things simple so the developer can focus on the things that are imperative to the requirements of the project.

public static AppDatabase getAppDatabase(Context context) {

  if (INSTANCE == null) {

      INSTANCE =

              Room.databaseBuilder(context.getApplicationContext(), AppDatabase.class, “user-database”)

                      // allow queries on the main thread.

                      // Don’t do this on a real app! See PersistenceBasicSample for an example.

                      .allowMainThreadQueries()

                      .build();

  }

  return INSTANCE;

}

}

We create a new class called appDatabase. Then we write the Room code to build the database by calling the databasebuilder() method and pass in the parameters like we need context of the application and pass in the database name in the parameters.

Data access object DAO

The data access object has all the methods/functions to access the database. It has all the CRUD operations. We need to manipulate data. So we apparently create a class called itemDao with @Dao annotation.

@Dao

public interface ItemsDao {

 

  @Insert(onConflict = OnConflictStrategy.IGNORE)

  long insertOneItemOnly(Item item);

 

  @Insert(onConflict = OnConflictStrategy.REPLACE)

  void insertMultipleItems(List<Item> items);

 

  @Query(“SELECT * FROM Item WHERE _id== :ItemID “)   // :ItemID is the parameter passed in function

  Item fetchItemFromID(int ItemID);

}

The code is intuitive.@Insert annotation tells the compiler that this is an insert method used to save data to a specific table. On conflict strategy means that if a conflict arises in insertion ignore it. The first method returns a long data type a number in case of success or failure of insertion. We can create almost any query by using @Query annotation just like in SQL. fetch item from id fetches the data based on passed parameter id and eventually returns the data object item.

Leave a Reply