Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
How to View and Locate Realm Database in Android Studio?
Next article icon

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

Last Updated : 09 Nov, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

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 dependency         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: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">      <!--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:


Next Article
How to View and Locate Realm Database in Android Studio?

C

chaitanyamunje
Improve
Article Tags :
  • Java
  • Android
Practice Tags :
  • Java

Similar Reads

  • How to Update Data in Realm Database in Android?
    In previous articles, we have seen adding and reading data from our realm database in Android. In that article, we were adding course details in our database and reading the data in the form of a list. In this article, we will take a look at updating this data in our android app.  What we are going
    7 min read
  • How to Create and Add Data to SQLite Database in Android?
    SQLite is another data storage available in Android where we can store data in the user's device and can use it any time when required. In this article, we will take a look at creating an SQLite database in the Android app and adding data to that database in the Android app. This is a series of 4 ar
    8 min read
  • How to Delete Data in Realm Database in Android?
    In the previous series of articles on the realm database, we have seen adding, reading, and updating data using the realm database in android. In that articles, we were adding course details, reading them, and updating them. In this article, we will take a look at deleting these course details from
    6 min read
  • How to Read Data from Realm Database in Android?
    In the previous article, we have seen adding data to the realm database in Android. In this article, we will take a look at reading this data from our Realm Database in the Android app.  What we are going to build in this article?  In this article, we will be simply adding a Button to open a new act
    8 min read
  • How to View and Locate Realm Database in Android Studio?
    Realm’s mobile database is an open-source, developer-friendly alternative to CoreData and SQLite. 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
    2 min read
  • How to Add Data to Back4App Database in Android?
    Prerequisite: How to Connect Android App with Back4App? Back4App is an online database providing platform that provides us services with which we can manage the data of our app inside the database. This is a series of 4 articles in which we are going to perform the basic CRUD (Create, Read, Update,
    4 min read
  • How to Update Data to SQLite Database in Android?
    We have seen How to Create and Add Data to SQLite Database in Android as well as How to Read Data from SQLite Database in Android. We have performed different SQL queries for reading and writing our data to SQLite database. In this article, we will take a look at updating data to SQLite database in
    10 min read
  • How to Read Data from SQLite Database in Android?
    In the 1st part of our SQLite database, we have seen How to Create and Add Data to SQLite Database in Android. In that article, we have added data to our SQLite Database. In this article, we will read all this data from the SQLite database and display this data in RecyclerView. What we are going to
    12 min read
  • How to Create and Add Data to SQLite Database in Android using Jetpack Compose?
    SQLite Database is another data storage available in Android where we can store data in the user’s device and can use it any time when required. In this article we will take a look on How to Create and add data to SQLite Database in Android using Jetpack Compose.  Step by Step ImplementationStep 1:
    9 min read
  • How to Save Data to the Firebase Realtime Database in Android?
    Firebase is one of the famous backend platforms which is used by so many developers to provide backend support to their applications and websites. It is the product of Google which provides services such as database, storage, user authentication, and many more. In this article, we will create a simp
    7 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences