Android realm | Android Tutorial on Realm Database

 

In this blog we will discuss about the usage of android Realm database in android app.So far we have learnt different local databases in android.

Local databases are used to store data in app level so as to maintain user required information available in offline state.When there a requirement to store details in the app without internet local database is the best option.

Now a days most of the social networking sites, job portals, online food ordering apps use these to store the data to provide faster services to user as data loading speed is reduced and faster service is provided.

 

Android realm database :

Using local databases provide a faster way to operate the apps and also reduce internet data consumption for reusable data.

Most of the data like images, videos, form data is majorly stored for reuse here in this blog we will go through the usage of android realm database.

 

Android realm video tutorial :

Go through the below tutorial for more detailed explanation.

 

Dependencies :

Add realm dependency in build.gradle (Project)

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

 

Apply plugin in build.gradle (Module: app)

apply plugin: 'realm-android'

 

Android realm Project Structure :

This image depicts the usage of android realm database project implementation.

android realm

 

MyApplication.java

Create a class extending Application where we initialize Android Realm Database.

 

Realm.init(this)

 

import android.app.Application
import io.realm.Realm

class MyApplication : Application() {
    override fun onCreate() {
        super.onCreate()
        Realm.init(this)
    }
}

 

DataModel.class

Now it’s a turn for creating variables in object class extending RealmObject()

import io.realm.RealmObject

open class DataModel : RealmObject() {
    var id = 0
    var name: String? = null
    var email: String? = null

}

 

data_input.xml

Here we declare input fields to enter the data into the database, considering 3 edittext’s to accept user input for id, name, email.

 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:padding="40dp">

    <EditText
        android:id="@+id/edt_id"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="number"
        android:hint="user id"/>

    <EditText
        android:id="@+id/edt_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:hint="user name"/>

    <EditText
        android:id="@+id/edt_email"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:hint="user email"/>

</LinearLayout>

 

activity_main.xml

Here we make use of data_input layout and add button’s to perform CRUD operations Create, Retrieve, Update, Delete on database.

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

    <include
        android:id="@+id/layout_include"
        layout="@layout/data_input"/>

    <LinearLayout
        android:id="@+id/layout"
        android:layout_below="@+id/layout_include"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="50dp"
        android:orientation="horizontal">

        <Button
            android:id="@+id/btn_insertdata"
            android:layout_width="0dp"
            android:layout_height="100dp"
            android:text="Insert Data"
            android:layout_weight="1"/>

        <Button
            android:id="@+id/btn_readdata"
            android:layout_width="0dp"
            android:layout_height="100dp"
            android:text="Read Data"
            android:layout_weight="1"/>

    </LinearLayout>

    <LinearLayout
        android:id="@+id/layout2"
        android:layout_below="@+id/layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

    <Button
        android:id="@+id/btn_updatedata"
        android:layout_width="0dp"
        android:layout_height="100dp"
        android:text="Update Data"
        android:layout_weight="1"/>

    <Button
        android:id="@+id/btn_deletedata"
        android:layout_width="0dp"
        android:layout_height="100dp"
        android:text="Delete Data"
        android:layout_weight="1"/>

    </LinearLayout>

</RelativeLayout>

 

MainActivity.java

Here we make use of the DataModel to make the database perform CRUD operation’s.

 

Initialize realm object

var realm: Realm? = null
realm = Realm.getDefaultInstance()

Initialize DataModel

val dataModel = DataModel()

 

Initialize button onClickListeners using Kotlin Synthetic Binding

 

btn_insertdata.setOnClickListener(this)
btn_readdata.setOnClickListener(this)
btn_updatedata.setOnClickListener(this)
btn_deletedata.setOnClickListener(this)

 

Add data to database :

Fetching the data from edittext and inserting to database using data model and adding data to android realm database.

 

realm!!.executeTransaction { realm -> realm.copyToRealm(dataModel) }

 

fun addData() {

    try {

        dataModel.id = edt_id.text.toString().toInt()
        dataModel.name = edt_name.text.toString()
        dataModel.email = edt_email.text.toString()

        realm!!.executeTransaction { realm -> realm.copyToRealm(dataModel) }

        clearFields()

        Log.d("Status","Data Inserted !!!")

    }catch (e:Exception){
        Log.d("Status","Something went Wrong !!!")
    }
}

 

Read data from Database :

Reading/ fetching data from database using data model class.

 

fun readData() {

    try {

        val dataModels: List<DataModel> =
            realm!!.where(DataModel::class.java).findAll()

        for (i in dataModels.indices) {
            edt_id?.setText("" + dataModels[i].id)
            edt_name?.setText(dataModels[i].name)
            edt_email?.setText(dataModels[i].email)
        }

        Log.d("Status","Data Fetched !!!")

    } catch (e: Exception) {
        Log.d("Status","Something went Wrong !!!")
    }
}

 

Update data to Database :

Update the existing data in database using data model.

 

fun updateData() {

    try {

        val id: Long = edt_id.text.toString().toLong()
    val dataModel =
        realm!!.where(DataModel::class.java).equalTo("id", id).findFirst()

    edt_name.setText(dataModel?.name)
    edt_email.setText(dataModel?.email)

        Log.d("Status","Data Fetched !!!")
    }catch (e:Exception){
        Log.d("Status","Something went Wrong !!!")
    }
}

 

Delete the data from Database :

With the help of the id we can delete the data from database using data model.

 

fun deleteData() {

    try {
        val id: Long = edt_id.text.toString().toLong()
    val dataModel =
        realm!!.where(DataModel::class.java).equalTo("id", id).findFirst()
    realm!!.executeTransaction {
        dataModel?.deleteFromRealm()
    }
        clearFields()

        Log.d("Status","Data deleted !!!")

    }catch (e:Exception){
        Log.d("Status","Something went Wrong !!!")
    }
}

 

Full Code :

Providing the full code for android realm database implementations.

package com.example.realmdatabase

import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import io.realm.Realm
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.data_input.*

class MainActivity : AppCompatActivity(), View.OnClickListener {

    var realm: Realm? = null
    val dataModel = DataModel()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        realm = Realm.getDefaultInstance()

        btn_insertdata.setOnClickListener(this)
        btn_readdata.setOnClickListener(this)
        btn_updatedata.setOnClickListener(this)
        btn_deletedata.setOnClickListener(this)

    }

    override fun onClick(v: View?) {

        when (v?.id) {

            R.id.btn_insertdata -> {
                addData()
            }

            R.id.btn_readdata -> {
                readData()
            }

            R.id.btn_updatedata -> {
                updateData()
            }

            R.id.btn_deletedata -> {
                deleteData()
            }
        }
    }

    fun deleteData() {

        try {
            val id: Long = edt_id.text.toString().toLong()
        val dataModel =
            realm!!.where(DataModel::class.java).equalTo("id", id).findFirst()
        realm!!.executeTransaction {
            dataModel?.deleteFromRealm()
        }
            clearFields()

            Log.d("Status","Data deleted !!!")

        }catch (e:Exception){
            Log.d("Status","Something went Wrong !!!")
        }
    }

    fun updateData() {

        try {

            val id: Long = edt_id.text.toString().toLong()
        val dataModel =
            realm!!.where(DataModel::class.java).equalTo("id", id).findFirst()

        edt_name.setText(dataModel?.name)
        edt_email.setText(dataModel?.email)

            Log.d("Status","Data Fetched !!!")
        }catch (e:Exception){
            Log.d("Status","Something went Wrong !!!")
        }
    }

    fun addData() {

        try {

            dataModel.id = edt_id.text.toString().toInt()
            dataModel.name = edt_name.text.toString()
            dataModel.email = edt_email.text.toString()

            realm!!.executeTransaction { realm -> realm.copyToRealm(dataModel) }

            clearFields()

            Log.d("Status","Data Inserted !!!")

        }catch (e:Exception){
            Log.d("Status","Something went Wrong !!!")
        }
    }

    fun readData() {

        try {

            val dataModels: List<DataModel> =
                realm!!.where(DataModel::class.java).findAll()

            for (i in dataModels.indices) {
                edt_id?.setText("" + dataModels[i].id)
                edt_name?.setText(dataModels[i].name)
                edt_email?.setText(dataModels[i].email)
            }

            Log.d("Status","Data Fetched !!!")

        } catch (e: Exception) {
            Log.d("Status","Something went Wrong !!!")
        }
    }

    fun clearFields(){

        edt_id.setText("")
        edt_name.setText("")
        edt_email.setText("")
    }
}

 

Android realm Output :

This screen depicts the usage of android realm database implementation.

 

android realm

If you have any queries in this tutorial on android realm database implementation let me know in comment section below.If you like this tutorial do like, share us for more interesting updates.

 

Show Buttons
Hide Buttons
Read previous post:
Firebase Firestore Android Tutorial- retrieve list data

  Firebase Firestore : Firebase firestore is used to store our data in this blog and retrieve it as a...

Close