Realm Database in Android


Introduction

There are several databases used in android for storing as well as retrieval of data such as SQLite, Room DB, Realm Database and many more. Realm Database is also one of the famous data storage services which uses SQLite to store the data within our android application. In this article we will take a look at using Realm Database in Android.

Implementation

We will be creating a simple application in which we will be displaying two text input fields. Users can enter his name and age from that field. Then we will also add a button which we will be using to save data to our database. On clicking on that button we will first validate whether the text input fields or not. If the text input fields are not null then we will add the data from text input fields in our realm database.

Step 1 : Creating a new project in Android Studio

Navigate to Android studio as shown in below screen. In the below screen click on New Project to create a new Android Studio Project.

After clicking on New Project you will get to see the below screen.

Inside this screen we have to simply select Empty Activity and click on Next. After clicking on next you will get to see the screen below.

Inside this screen we have to simply specify the project name. Then the package name will be generated automatically.

Note : Make sure to select the Language as Java.

After specifying all the details click on Finish to create a new Android studio project.

Once our project has been created we will get to see 2 files which are open i.e activity_main.xml and MainActivity.java file.

Step 2 : Adding the dependency in project level build.gradle file

Navigate to build.gradle (project level) file. Inside this add below dependencies in dependencies section.

classpath "io.realm:realm-gradle-plugin:10.3.1"

Step 3 : Adding the plugin in the module level build.gradle file

Navigate to build.gradle (module level) file. Inside this add below code on top of that file.

apply plugin: 'realm-android'

After that in the same file add below code just below the android section.

realm {
   syncEnabled = true
}

After adding the above dependencies simply sync your project to install it.

Step 4 : Creating a new java class for initializing the Realm Database

Navigate to app>java>your app’s package name>Right click on it>New>Java class and name it as RealmDatabase and add below code to it. Comments are added in the code to get to know in detail.

package com.example.java_test_application;
import android.app.Application;
import io.realm.Realm;
public class RealmDatabase extends Application {
   @Override
   public void onCreate() {
      super.onCreate();
      // on below line we are initializing our real m database.
      Realm.init(this);
      // on below line we are creating a variable for realm configuration and initializing it.
      RealmConfiguration config = new RealmConfiguration.Builder()
         // below line is to allow write
         // data to database on ui thread.
         .allowWritesOnUiThread(true)
         // below line is to delete realm
         // if migration is needed.
         .deleteRealmIfMigrationNeeded()
         // at last we are calling a build method to generate the configurations.
         .build();
      // on below line we are setting the default
      // configuration to our realm database.
      Realm.setDefaultConfiguration(config);
   }
}

Explanation : In the above code we are initializing the realm database and setting the default configuration for it inside the onCreate method.

Step 5 : Defining this class of RealmDatabase in AndroidManifest.xml file

Navigate to app>AndroidManifest.xml file and add below line in the application tag.

android:name=".RealmDatabase"

Step 6 : Working with activity_main.xml

Navigate to activity_main.xml. If this file is not visible. To open this file. In the left pane navigate to app>res>layout>activity_main.xml to open this file. After opening this file. Add the below code to it. Comments are added in the code to get to know in detail.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:orientation="vertical"
   tools:context=".MainActivity">

   <!-- on below line creating a text view for displaying the heading of our application -->
   <TextView
       android:id="@+id/idTVHeading"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_marginStart="10dp"
       android:layout_marginTop="100dp"
       android:layout_marginEnd="10dp"
       android:gravity="center"
       android:padding="4dp"
       android:text="Realm Database in Android"
       android:textAlignment="center"
       android:textColor="@color/black"
       android:textSize="20sp"
       android:textStyle="bold" />

   <!-- on below line creating edit text for name -->
   <EditText
       android:id="@+id/idEdtName"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_below="@id/idTVHeading"
       android:layout_margin="10dp"
       android:hint="Enter Name" />

   <!-- on below line creating edit text for age -->
   <EditText
       android:id="@+id/idEdtAge"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_below="@id/idEdtName"
       android:layout_margin="10dp"
       android:hint="Enter Age" />

   <!-- on below line creating a button for adding data -->
   <Button
       android:id="@+id/idBtnAddData"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_below="@id/idEdtAge"
       android:layout_margin="10dp"
       android:padding="4dp"
       android:text="Add Data to Database"
       android:textAllCaps="false" />
</RelativeLayout>

Explanation : In the above code we are creating a root layout as a Relative Layout. Inside this layout we are creating a text view which is used to display the heading of our application. After that we are creating two edit text fields which are used to take the input from the user as name and age. After that we are creating a button which is use to add the data to our Realm Database.

Step 7 : Creating a Modal class for our data

Navigate to app>java>your app’s package name>Right click on it>New Java class and name it as DataObject and add below code to it. Comments are added in the code to get to know in detail.

package com.example.java_test_application;
import io.realm.RealmObject;
import io.realm.annotations.PrimaryKey;
public class DataObject extends RealmObject{
   // on below line creating a long variable for id of each item of db which will be unique.
   @PrimaryKey
   private long id;
   // on below line creatig a variable for name and age.
   private String name;
   private String age;
   // on below line we are creating getter and setter methods for name and age variables.
   public String getName() {
       return name;
   }
   public void setName(String name) {
       this.name = name;
   }
   public String getAge() {
       return age;
   }
   public void setAge(String age) {
       this.age = age;
   }
   // on below line we are
   // creating an empty constructor for Data Object class..
   public DataObject() {
   }
}

Explanation : In the above code we are creating three variables, first is for id of each database entry, then creating variables for name and age. After that we are creating an empty constructor and lastly creating getter and setter methods for both name and age variable.

Step 8 : Working with MainActivity.java file

Navigate to MainActivity.java. If this file is not visible. To open this file. In the left pane navigate to app>res>layout>MainActivity.java to open this file. After opening this file. Add the below code to it. Comments are added in the code to get to know in detail.

package com.example.java_test_application;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.StackView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.util.ArrayList;
import java.util.List;
import io.realm.gradle.Realm;
public class MainActivity extends AppCompatActivity {
   // creating variables for edit text on below line.
   private EditText nameEdt, ageEdt;
   // creating variable for button on below line.
   private Button addDataBtn;
   // on below line creating a variable for realm.
   private Realm realm;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);
       // initializing variables for edit text on below line.
       nameEdt = findViewById(R.id.idEdtName);
       ageEdt = findViewById(R.id.idEdtAge);
       // initializing variables for button on below line.
       addDataBtn = findViewById(R.id.idBtnAddData);
       // on below line initializing the variable for realm.
       realm = Realm.getDefaultInstance();
       // adding click listener for button on below line.
       addDataBtn.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View v) {
               // on below line validating if name and age is empty or not.
               if (nameEdt.getText().toString().isEmpty() && ageEdt.getText().toString().isEmpty()) {
                   // if both name and age is empty we are displaying a toast message on below line.
                   Toast.makeText(getApplicationContext(), "Please enter your name and age", Toast.LENGTH_SHORT).show();
               } else {
                   // name and age is not empty in thus case we are adding data to our database.
                   addDataToDB(nameEdt.getText().toString(), ageEdt.getText().toString());
                   // on below line displaying toast message as data has been added to database..
                   Toast.makeText(MainActivity.this, "Data has been added to database..", Toast.LENGTH_SHORT).show();
               }
           }
       });
   }
   private void addDataToDB(String name, String age) {
       // on below line creating and initializing our data object class
       DataObject dataObject = new DataObject();
       // on below line we are getting id for the course which we are storing.
       Number id = realm.where(DataObject.class).max("id");
       // on below line we are
       // creating a variable for our id.
       long nextId;
       // validating if id is null or not.
       if (id == null) {
           // if id is null
           // we are passing it as 1.
           nextId = 1;
       } else {
           // if id is not null then
           // we are incrementing it by 1
           nextId = id.intValue() + 1;
       }
       // on below line setting data for our modal class
       dataObject.setName(name);
       dataObject.setAge(age);
       // on below line we are calling a method to execute a transaction.
       realm.executeTransaction(new Realm.Transaction() {
           @Override
           public void execute(Realm realm) {
               // inside on execute method we are calling a method
               // to copy to real m database from our modal class.
               realm.copyToRealm(modal);
           }
       });
   }
}

Explanation : In the above code firstly we are creating variables for edit text, button and realm database. Now we will get to see the onCreate method. This is the default method of every android application. This method is called when the application view is created. Inside this method we are setting the content view i.e the layout file named activity_main.xml to set the UI from that file. Inside the onCreate method we are initializing the button and edit text variables with the ids which we have given in our activity_main.xml file. Along with that we are also initializing the variables for the realm database. After that we are adding an on click listener for our add data button. Inside the on click listener method we are firstly validating whether the text input field is empty or not. We are checking whether the name and age edit text is empty. If both of them are empty then we are displaying a toast message. In the else condition we are simply calling addDatatoDB method which is used to add data to our realm database.

Inside the addDatatoDB method we are firstly creating and initializing variables for DataObject. After that we are creating a number which will provide us with the id. Then we are setting the data from our edit text such as name and age to our object class variable. Then we are calling an execute transition method which is used to add data from application to database. Lastly inside the on click method of our button we are displaying a toast message as data added to our database.

After adding the above code now we have to simply click on the green icon in the top bar to run our application on a mobile device.

Note : Make sure you are connected to your real device or emulator.

Output

Conclusion

In this article we have taken a look on What is Realm Database and How can use it to store data within an android application.

Updated on: 09-May-2023

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements