Android local data storage - room database
The Room persistence library is part of jetpack libraries. It provides an abstraction layer over SQLite to allow fluent database access while harnessing the full power of SQLite.
Benefits of using room library instead of the traditional SQLite in Android:
Less boilerplate code
A wrapper over SQLite
Provides compile time verification of SQLIte queries
Supports LiveData
Main modules of room database
Entities - represent tables in your app's database
DAO - provide methods that your app can use to query, update, insert, and delete data in the database
Database - that holds the database and serves as the main access point for the underlying connection to your app's persisted data
Lets create a sample application which stores user information (First name and Last name) into the database.
Step 1 - Create users Entities
A class model to define how the table in the db will look like
@Entity
public class User {
@PrimaryKey(autoGenerate = true)
public int uid;
@ColumnInfo(name = "first_name")
public String firstName;
@ColumnInfo(name = "last_name")
public String lastName;
public User(){
}
public User(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
}
Step 2 - Create DAO
Interface to all the db CRUD operations
@Dao
public interface UserDao {
@Query("SELECT * FROM user")
LiveData<List<User>> getAll();
@Query("SELECT * FROM user WHERE uid IN (:userIds)")
List<User> loadAllByIds(int[] userIds);
@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);
}
Step 3 - Create Database
Abstract database class, whose actual implementation will be created by the ROOM library module.
@Database(entities = {User.class}, version = 1)
public abstract class AppDatabase extends RoomDatabase {
public abstract UserDao userDao();
}
Pictorial representation
Step 4 Creating a ViewModel (of MVVM)
View Model provides:
Access to the database instance, which can be used to update the db
Observable object (LiveData object), which can then be observed by UI to make changes in view.
public class AppViewModel extends AndroidViewModel {
AppDatabase db;
LiveData<List<User>> users;
public AppViewModel(@NonNull Application application) {
super(application);
db = Room.databaseBuilder(application,
AppDatabase.class, "database-name").build();
users = db.userDao().getAll();
}
public void insertData(User user){
db.userDao().insertAll(user);
}
}
Step 5 Creating an UI to show/update views
public class MainActivity extends AppCompatActivity {
AppViewModel viewModel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewModel = new ViewModelProvider(this).get(AppViewModel.class);
viewModel.users.observe(this, users -> {
Log.v("RAJAN","Added : "+ users.get(users.size()-1).firstName); });
Button btn = findViewById(R.id.btn1);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
new Thread(new Runnable() {
@Override
public void run() {
viewModel.insertData(new User("Rajan","Lal"));
}
}).start();
}
});
}
}
Above we can see how an Activity can use ViewModel object to listen for any changes in the database. In above sample, it just logs the entry for simplicity. Also it uses viewmodel object to insert new data to the data base.
Complete overview of the architecture
Conclusion
The article explains how to use the Room persistence library in Android to efficiently handle database operations with less boilerplate code. It outlines the benefits of Room, such as compile-time verification and LiveData support. The guide walks through creating a sample app to store and manage user information using Room entities, DAO, and database classes, along with implementing a ViewModel to interact with the UI and perform database operations.
Happy learning and happy coding!!!!!!!!!