This is android realm database tutorial.
Realm is an open source database that can be used to store data locally in android. It is used by over 100k developers and is a good alternative of SQLite.
In this tutorial I will teach you how to use realm database in android.
Android Realm Database Tutorial
Installation
Before using realm we have to add it to our project.
Go to project level build.gradle file and add following line under dependencies section.
classpath "io.realm:realm-gradle-plugin:2.2.1"
Now go to app level build.gradle file and add following line at top.
apply plugin: 'realm-android'
Sync your project.
At the time of making this tutorial the current version of realm is 2.2.1. Read this to know how to add latest version to your project.
Creating Realm
When the app is launched we have to initialize realm. It should be done only once.
Realm.init(this);
To get realm instance we have to use getDefaultInstance() method.
Realm realm = Realm.getDefaultInstance();
Models
Model classes are used for storing data in realm. A realm model class can be created by extending RealmObject class.
Suppose we want to store details of student then the model class can be created in following way.
import io.realm.RealmObject; public class Student extends RealmObject { private int roll_no; private String name; public int getRoll_no() { return roll_no; } public void setRoll_no(int roll_no) { this.roll_no = roll_no; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
In this way you can have several model classes in your project.
For making any variable primary key just add @PrimaryKey annotation before it.
Write
Any write, update or delete operation should be performed within beginTransaction() and commitTransaction() methods.
Let say we want to add a student data then it can be done in following way.
realm.beginTransaction(); Student student = realm.createObject(Student.class); student.setRoll_no(20); student.setName("neeraj mishra"); realm.commitTransaction();
Read
All students data can be retrieved in following way. For accessing the records just iterate through RealmResults inside a loop.
RealmResults<Student> results = realm.where(Student.class).findAll(); for(Student student : results){ System.out.println(student.getRoll_no() + " " + student.getName()); }
Realm provides several other methods for sorting the result. Suppose you want to fetch student with roll number 20.
RealmResults<Student> results = realm.where(Student.class).equalTo("roll_no", 20).findAll();
Update
For updating a record first fetch it and then change the value of object using setter methods. Suppose you want to change the name of student with roll number 20 then it can be done in following way.
RealmResults<Student> results = realm.where(Student.class).equalTo("roll_no", 20).findAll(); realm.beginTransaction(); for(Student student : results){ student.setName("neeraj mishra"); } realm.commitTransaction();
Delete
Realm provides several methods for deleting a record.
RealmResults<Student> results = realm.where(Student.class).findAll(); realm.beginTransaction(); // remove single match results.deleteFirstFromRealm(); results.deleteLastFromRealm(); // remove a single object Student student = results.get(5); student.deleteFromRealm(); // Delete all matches results.deleteAllFromRealm(); realm.commitTransaction();
Android Realm Database Example
Below I have shared one example that manages student information using realm database.
Create an android studio project with package name com.androidrealm.
Create a model class with following code.
Student.java
package com.androidrealm; import io.realm.RealmObject; public class Student extends RealmObject { private int roll_no; private String name; public int getRoll_no() { return roll_no; } public void setRoll_no(int roll_no) { this.roll_no = roll_no; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
Create an activity and add following code.
activity_main.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:padding="15dp" tools:context="com.androidrealm.MainActivity" android:orientation="vertical"> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Enter Roll No" android:id="@+id/roll_no"/> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Enter Name" android:id="@+id/name"/> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Add" android:id="@+id/add" android:onClick="clickAction"/> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="View" android:id="@+id/view" android:onClick="clickAction"/> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Update" android:id="@+id/update" android:onClick="clickAction"/> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Delete" android:id="@+id/delete" android:onClick="clickAction"/> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/text"/> </LinearLayout>
MainActivity.java
package com.androidrealm; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import io.realm.Realm; import io.realm.RealmResults; public class MainActivity extends AppCompatActivity { Button add, view, update, delete; EditText roll_no, name; TextView text; Realm realm; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); add = (Button)findViewById(R.id.add); view = (Button)findViewById(R.id.view); update = (Button)findViewById(R.id.update); delete = (Button)findViewById(R.id.delete); roll_no = (EditText)findViewById(R.id.roll_no); name = (EditText)findViewById(R.id.name); text = (TextView)findViewById(R.id.text); Realm.init(this); realm = Realm.getDefaultInstance(); } public void clickAction(View view){ switch (view.getId()){ case R.id.add: addRecord(); break; case R.id.view: viewRecord(); break; case R.id.update: updateRecord(); break; case R.id.delete: deleteRecord(); } } public void addRecord(){ realm.beginTransaction(); Student student = realm.createObject(Student.class); student.setRoll_no(Integer.parseInt(roll_no.getText().toString())); student.setName(name.getText().toString()); realm.commitTransaction(); } public void viewRecord(){ RealmResults<Student> results = realm.where(Student.class).findAll(); text.setText(""); for(Student student : results){ text.append(student.getRoll_no() + " " + student.getName() + "\n"); } } public void updateRecord(){ RealmResults<Student> results = realm.where(Student.class).equalTo("roll_no", Integer.parseInt(roll_no.getText().toString())).findAll(); realm.beginTransaction(); for(Student student : results){ student.setName(name.getText().toString()); } realm.commitTransaction(); } public void deleteRecord(){ RealmResults<Student> results = realm.where(Student.class).equalTo("roll_no", Integer.parseInt(roll_no.getText().toString())).findAll(); realm.beginTransaction(); results.deleteAllFromRealm(); realm.commitTransaction(); } @Override protected void onDestroy() { realm.close(); super.onDestroy(); } }
Save and run the project.
Screenshot
To learn more about realm you can read realm android docs at https://realm.io/docs/java/latest/
Comment below if you have any queries or found any information incorrect in above android realm tutorial.
Hie Neeraj,Well I Need Your Guide in Android Development.Actually I ‘m Doing a Management Project in Android Studio.It will be more better if i can talk to you on phone .So that I can clearly describe my project to you.
Hey Bhupendra contact me on facebook if you need any help or you can send email at sareneeru94@gmail.com
hello..
can you help me in guiding in how to read from local realm database in android.
I have used that database in my ios app but now I have exported it and want to use it in the android app
as well.
kindly share your thoughts if you can help me in that ..
Thanks in advance!
what is realm differ from firebase database ?
It is faster than sqlite, you can check more differences at below link
http://stackoverflow.com/questions/37151580/realm-vs-sqlite-for-mobile-development
Thanks Buddy
That was so simple && very good, Tnx Man.
clickAction is a method of realm ?
No, it is a user defined method bcz I have used onClick attribute in button, see the activity_main.xml file.
Thanx..it’s working now.
Hi,
there are no errors. and successfully Gradle build finished.
but, when I enter roll number and name then click on Add or any button we have it crashes and saying the app has stopped.
plz helip me…
iam trying to implement delete and update command in the recyclerview but the app is crashing could you please help me out in this matter?
Very good example . Can please give me demo of this app with realm object server with CRUD operation ?
dope stuff can you do sth on how to push this data to online server
awesome explanation bro
thanks for this .
i want to add column in to my existing entity student how can i do that one?
in room we use migration is anything like that in realm??
hi .. can u plz explain android test (UI test) sample code with brief explanation and code coverage