Skip to content
Related Articles

Related Articles

Improve Article

How to Install and Add Data to Realm Database in Android?

  • Last Updated : 30 Mar, 2021

Realm Database is a service which is provided by MongoDb which is used to store data in users device locally. With the help of this data can be stored easily in users’ devices and can be accessed easily. We can use this database to store data in the user’s device itself. This is a series of 4 articles in which we are going to perform the basic CRUD (Create, Read, Update, and Delete) operation with Realm Database in Android. We are going to cover the following 4 articles in this series:

  1. How to Install and Add Data to Realm Database in Android?
  2. How to Read Data from Realm Database in Android?
  3. How to Update Data to Realm Database in Android?
  4. How to Delete Data in Realm Database in Android?

In this article, we will take a look at installing and adding data to the Realm Database in Android. 

How Data is being stored in the Realm database?  

Data is stored in the Realm database in the form of tables. When we stored this data in our Realm database it is arranged in the form of tables that are similar to that of an Excel sheet. Below is the representation of our Realm database which we are storing in our Realm database. 

What we are going to build in this article?

We will be building a simple application in which we will be adding data to the Realm database. We will be creating a database for adding course names, course descriptions, and course duration. We will be saving all this data in our Realm database. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language.  



Step by Step Implementation

Step 1: Create a New Project

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.

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

Navigate to the app > Gradle Scripts > build.gradle (Project) and add classpath dependency in the dependencies section. You can get to see dependency in the below section. 

dependencies {
        classpath "com.android.tools.build:gradle:4.1.2"
        
        // add below dependancy
        classpath "io.realm:realm-gradle-plugin:10.3.1"

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
}

After adding this now navigates to build.gradle (Module) and add the below code to it. Add plugin on top of this file. 

apply plugin: 'realm-android'     

After that add the below code above the dependencies section. 

realm {
    syncEnabled = true
}

Now sync your project, and now we will move towards creating a new java class. Below is the complete code for the build.gradle (Module) file:

Java






plugins {
    id 'com.android.application'
}
 
apply plugin: 'realm-android'
 
android {
    compileSdkVersion 30
    buildToolsVersion "30.0.3"
    ndkVersion '21.3.6528147'
 
    defaultConfig {
        applicationId "com.example.realm"
        minSdkVersion 23
        targetSdkVersion 30
        versionCode 1
        versionName "1.0"
 
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
 
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}
 
realm {
    syncEnabled = true
}
 
dependencies {
    implementation 'androidx.appcompat:appcompat:1.2.0'
    implementation 'com.google.android.material:material:1.3.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
    testImplementation 'junit:junit:4.+'
    androidTestImplementation 'androidx.test.ext:junit:1.1.2'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
}

Step 3: Creating a new java class for initializing the realmDatabase 

Navigate to the app > java > your app’s package name > Right-click on it > New > Java class and name it as RealmDb and add the below code to it. 

Java




import android.app.Application;
 
import io.realm.Realm;
import io.realm.RealmConfiguration;
 
public class RealmDb extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
         
        // on below line we are
        // initializing our realm database.
        Realm.init(this);
         
        // on below line we are setting realm configuration
        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 method to build.
                        .build();
        // on below line we are setting
        // configuration to our realm database.
        Realm.setDefaultConfiguration(config);
    }
}

Step 4: Defining this class in the AndroidManifest.xml file

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

android:name=”.RealmDb”

Now we will move towards working with activity_main.xml. 

Step 5: Working with the activity_main.xml file

Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. 

XML






<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">
 
    <!--Edit text to enter course name-->
    <EditText
        android:id="@+id/idEdtCourseName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:hint="Enter course Name" />
 
    <!--edit text to enter course duration-->
    <EditText
        android:id="@+id/idEdtCourseDuration"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:hint="Enter Course Duration" />
 
    <!--edit text to display course tracks-->
    <EditText
        android:id="@+id/idEdtCourseTracks"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:hint="Enter Course Tracks" />
 
    <!--edit text for course description-->
    <EditText
        android:id="@+id/idEdtCourseDescription"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:hint="Enter Course Description" />
 
    <!--button for adding new course-->
    <Button
        android:id="@+id/idBtnAddCourse"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:text="Add Course"
        android:textAllCaps="false" />
 
</LinearLayout>

Step 6: Creating a modal class for storing our data

Navigate to the app > java > your app’s package name > Right-click on it > New > Java class and name it as DataModal and add the below code to it. 

Java




import io.realm.RealmObject;
import io.realm.annotations.PrimaryKey;
 
public class DataModal extends RealmObject {
    // on below line we are creating our variables
    // and with are using primary key for our id.
    @PrimaryKey
    private long id;
    private String courseName;
    private String courseDescription;
    private String courseTracks;
    private String courseDuration;
 
    // on below line we are
    // creating an empty constructor.
    public DataModal() {
    }
 
    // below line we are
    // creating getter and setters.
    public String getCourseTracks() {
        return courseTracks;
    }
 
    public void setCourseTracks(String courseTracks) {
        this.courseTracks = courseTracks;
    }
 
    public long getId() {
        return id;
    }
 
    public void setId(long id) {
        this.id = id;
    }
 
    public String getCourseName() {
        return courseName;
    }
 
    public void setCourseName(String courseName) {
        this.courseName = courseName;
    }
 
    public String getCourseDescription() {
        return courseDescription;
    }
 
    public void setCourseDescription(String courseDescription) {
        this.courseDescription = courseDescription;
    }
 
    public String getCourseDuration() {
        return courseDuration;
    }
 
    public void setCourseDuration(String courseDuration) {
        this.courseDuration = courseDuration;
    }
}

Step 7: Working with the MainActivity.java file

Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.

Java




import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
 
import androidx.appcompat.app.AppCompatActivity;
 
import io.realm.Realm;
 
public class MainActivity extends AppCompatActivity {
 
    // creating variables for our edit text
    private EditText courseNameEdt, courseDurationEdt, courseDescriptionEdt, courseTracksEdt;
    private Realm realm;
     
    // creating a strings for storing
    // our values from edittext fields.
    private String courseName, courseDuration, courseDescription, courseTracks;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
         
        // initializing our edittext and buttons
        realm = Realm.getDefaultInstance();
        courseNameEdt = findViewById(R.id.idEdtCourseName);
        courseDescriptionEdt = findViewById(R.id.idEdtCourseDescription);
        courseDurationEdt = findViewById(R.id.idEdtCourseDuration);
         
        // creating variable for button
        Button submitCourseBtn = findViewById(R.id.idBtnAddCourse);
        courseTracksEdt = findViewById(R.id.idEdtCourseTracks);
        submitCourseBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                 
                // getting data from edittext fields.
                courseName = courseNameEdt.getText().toString();
                courseDescription = courseDescriptionEdt.getText().toString();
                courseDuration = courseDurationEdt.getText().toString();
                courseTracks = courseTracksEdt.getText().toString();
                 
                // validating the text fields if empty or not.
                if (TextUtils.isEmpty(courseName)) {
                    courseNameEdt.setError("Please enter Course Name");
                } else if (TextUtils.isEmpty(courseDescription)) {
                    courseDescriptionEdt.setError("Please enter Course Description");
                } else if (TextUtils.isEmpty(courseDuration)) {
                    courseDurationEdt.setError("Please enter Course Duration");
                } else if (TextUtils.isEmpty(courseTracks)) {
                    courseTracksEdt.setError("Please enter Course Tracks");
                } else {
                    // calling method to add data to Realm database..
                    addDataToDatabase(courseName, courseDescription, courseDuration, courseTracks);
                    Toast.makeText(MainActivity.this, "Course added to database..", Toast.LENGTH_SHORT).show();
                    courseNameEdt.setText("");
                    courseDescriptionEdt.setText("");
                    courseDurationEdt.setText("");
                    courseTracksEdt.setText("");
                }
            }
        });
    }
 
    private void addDataToDatabase(String courseName, String courseDescription, String courseDuration, String courseTracks) {
         
        // on below line we are creating
        // a variable for our modal class.
        DataModal modal = new DataModal();
         
        // on below line we are getting id for the course which we are storing.
        Number id = realm.where(DataModal.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 we are setting the
        // data entered by user in our modal class.
        modal.setId(nextId);
        modal.setCourseDescription(courseDescription);
        modal.setCourseName(courseName);
        modal.setCourseDuration(courseDuration);
        modal.setCourseTracks(courseTracks);
         
        // 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);
            }
        });
    }
}

Now run your app and see the output of the app. In this article, you will only able to add the data to our database. In the next article, we will take a look at reading this data. 

Output:

After successfully executed the code enter the required data inside the EditText. Most importantly if you want to know How to View and Locate the Realm Database in Android Studio then please refer to this article. And you can see below this is how the data stored in the Realm database.
 

Below is the complete project file structure after performing the installation and add operation:

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.




My Personal Notes arrow_drop_up
Recommended Articles
Page :