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]()
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
![Android Realm Database Example]()
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.
The post Android Realm Database Tutorial appeared first on The Crazy Programmer.