Android’de Realm Database Kullanımı

• Tuğba Üstündağ • 7 dk okuma

Yazılım projelerinde planlama çalışmaları yapılırken projeye uygun veritabanını seçmek çok önemlidir.
Bu makalede; tüm platformlarda kullanılabilen, hızlı ve SQLite yapısının alternatifi olan Realm veritabanını Android uygulamada nasıl kullanabileceğimizi anlatacağım.

Örnek uygulamamızı inceleyelim.

Realm Database Nedir?

Swift / Objective-C (iOS), Java / Kotlin (Android), C#, and JavaScript yazılım yapılarının tamamında kullanabilen veritabanıdır. Realm ‘in performansı SQLite gibi veritabanı yapılarından daha yüksektir. Çünkü Realm MongoDB alt yapısını kullanmaktadır. Bildiğiniz üzere MongoDB veritabanı yapısı daha çok büyük projelerde tercih edilmektedir. Bu doğrultuda Realm veritabanı da büyük projelerde, SQLite ise az veri içeren projelerde tercih edebilirsiniz. Bu konuda fikir edinmek için sorgu hızıyla ilgili karşılaştırma grafiğini inceleyebilirsiniz.

1-Projede Gerekli Bazı Ayarlar

  1. Projenizin ana dizinindeki build.gradle dosyasını açmalısınız. dependencies blogları arasına aşağıdaki kodu ekleyerek Realm kütüphanesini yüklemelisiniz.
    classpath "io.realm:realm-gradle-plugin:10.6.0"
  2. Projemin app dizinin altındaki build.gradle dosyasını açıyoruz. plugins blogları arasına aşağıdaki kodu eklemelisiniz.
    id 'realm-android'
  3. AndroidManifest dosyamıza ekleyeceğimiz ayarı diğer adımlarda bahsedeceğim.

2- Java’da Realm Veritabanı Kullanımı

İlk öncelikle kullanacağımız veritabanı tablosunda hangi tiplerde veriler içereceğini tanımlamamız gerekir. Tablodaki veri tiplerini tanımlama RealmObject sınıfından faydalanarak yapılır. Örneğimizde Student adında bir sınıf oluşturduk. Bu sınıfı da RealmObject yapısından kalıtım aldık. Student sınıfında tanımlanan değişkenler artık tablodaki veri tipleridir.

import io.realm.RealmObject;
public class Student extends RealmObject {
    int roll_no;
    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;
    }
}

Realm veritabanıyla alakalı bazı konfigürasyonları yapmamız gerekmektedir.  Bunun için RealmApplication adında bir sınıf oluşturup Application yapısından kalıtım yaptım.

import android.app.Application;
import io.realm.Realm;
import io.realm.RealmConfiguration;
public class RealmApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        Realm.init(getApplicationContext());
        RealmConfiguration config =
                new RealmConfiguration.Builder()
                        .deleteRealmIfMigrationNeeded()
                        .build();
        Realm.setDefaultConfiguration(config);
    }
}

Sonrasında AndroidManifest dosyamızda application tag özelllikleri arasına android:name=”.RealmApplication” tanımlamasını eklemeliyiz. Böylelikle uygulama çalışır çalışmaz RealmApplication sınıfını tanıyabilecek.

Veritabanına veri ekleme, güncelleme ve silme yazılabilir eylemdir. Realm’ de yazılabilir sorgu tipleri çalıştıracaksak beginTransaction ile koda başlayıp, sorguyu yazdıktan sonra da commitTransaction ile sonlandırmayı yapmamız gerekir.

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.*;
import io.realm.*;
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.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 = Realm.getDefaultInstance();

    }
    //Her button için setOnClickListener kodunu uzun uzun yazmak yerine xmlde onClick özelliğine clickAction metodunu tanımladım.
    //Böylelikle kısa ve daha anlaşılır kod yazmış oldum.
    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 sınıfında belirlenin objeleri createObject ile oluşturduk.
        Student student = realm.createObject(Student.class);
        //Tablo sütunlarına verileri ekliyoruz...
        student.setRoll_no(Integer.parseInt(roll_no.getText().toString()));
        student.setName(name.getText().toString());

        realm.commitTransaction();
    }
    public void viewRecord(){
        //Tüm kayıtları getiren sorgu
        RealmResults<Student> results = realm.where(Student.class).findAll();
        
        //Kayıtların arayüzde gösterilmesi 
        for(Student student : results){
            text.append("Rol No: "+student.getRoll_no() + "\nName: " + student.getName() + "\n");
        }
    }
    public void updateRecord(){
        realm.beginTransaction();
        //roll_no sutünundaki değer edittexten gelen değeri eşitse ilgili kayıtı güncellenecek
        RealmResults<Student> results = realm.where(Student.class).equalTo("roll_no", Integer.parseInt(roll_no.getText().toString())).findAll();
        
        for(Student student : results){
            student.setName(name.getText().toString());
        }
        realm.commitTransaction();
    }
    public void deleteRecord(){
        realm.beginTransaction();
        //roll_no sutünundaki değer edittexten gelen değeri eşitse ilgili kayıt silenecek
        RealmResults<Student> results = realm.where(Student.class).equalTo("roll_no", Integer.parseInt(roll_no.getText().toString())).findAll();
        results.deleteAllFromRealm();

        realm.commitTransaction();
    }
    @Override
    protected void onDestroy() {
        realm.close();
        super.onDestroy();
    }
}

3- Arayüz kodlama

Son olarak tasarım kodlarımızı yazalım.

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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">

    <EditText
        android:id="@+id/roll_no"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="60dp"
        android:ems="10"
        android:hint="Roll No"
        android:inputType="textPersonName"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:ems="10"
        android:hint="Name"
        android:inputType="textPersonName"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.497"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/roll_no" />

    <Button
        android:id="@+id/add"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="100dp"
        android:layout_marginTop="20dp"
        android:layout_marginEnd="100dp"
        android:text="Add"
        android:onClick="clickAction"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/name" />

    <Button
        android:id="@+id/view"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="100dp"
        android:layout_marginTop="20dp"
        android:layout_marginEnd="100dp"
        android:text="view"
        android:onClick="clickAction"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/add" />

    <Button
        android:id="@+id/update"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="100dp"
        android:layout_marginTop="20dp"
        android:layout_marginEnd="100dp"
        android:text="update"
        android:onClick="clickAction"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/view" />

    <Button
        android:id="@+id/delete"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="100dp"
        android:layout_marginTop="20dp"
        android:layout_marginEnd="100dp"
        android:text="delete"
        android:onClick="clickAction"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/update" />

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="40dp"
        android:textColor="#000000"
        android:textSize="22sp"
        android:textStyle="bold"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/delete" />
</androidx.constraintlayout.widget.ConstraintLayout>

Tüm proje kodlarına github linkinden ulaşabilirsiniz.