Android 中的 Realm 資料庫


簡介

Android 中有幾種用於儲存和檢索資料的資料庫,例如 SQLite、Room DB、Realm 資料庫等等。Realm 資料庫也是一種著名的資料儲存服務,它使用 SQLite 在我們的 Android 應用程式中儲存資料。在本文中,我們將探討如何在 Android 中使用 Realm 資料庫。

實現

我們將建立一個簡單的應用程式,其中我們將顯示兩個文字輸入欄位。使用者可以從這些欄位中輸入姓名和年齡。然後,我們還將新增一個按鈕,我們將使用它來將資料儲存到我們的資料庫。單擊該按鈕後,我們將首先驗證文字輸入欄位是否為空。如果文字輸入欄位不為空,則我們將文字輸入欄位中的資料新增到我們的 Realm 資料庫中。

步驟 1:在 Android Studio 中建立一個新專案

導航到 Android Studio,如下面的螢幕所示。在下面的螢幕中,單擊“新建專案”以建立一個新的 Android Studio 專案。

單擊“新建專案”後,您將看到下面的螢幕。

在此螢幕中,我們只需選擇“空活動”並單擊“下一步”。單擊“下一步”後,您將看到下面的螢幕。

在此螢幕中,我們只需指定專案名稱。然後包名將自動生成。

注意:確保將語言選擇為 Java。

指定所有詳細資訊後,單擊“完成”以建立一個新的 Android Studio 專案。

建立專案後,我們將看到兩個開啟的檔案,即 activity_main.xml 和 MainActivity.java 檔案。

步驟 2:在專案級 build.gradle 檔案中新增依賴項

導航到 build.gradle(專案級)檔案。在此檔案中,在 dependencies 部分新增以下依賴項。

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

步驟 3:在模組級 build.gradle 檔案中新增外掛

導航到 build.gradle(模組級)檔案。在此檔案中,在檔案頂部新增以下程式碼。

apply plugin: 'realm-android'

然後在同一檔案中,在 android 部分下方新增以下程式碼。

realm {
   syncEnabled = true
}

新增上述依賴項後,只需同步您的專案以安裝它。

步驟 4:建立一個新的 Java 類來初始化 Realm 資料庫

導航到 app>java>您的應用程式包名>右鍵單擊它>新建>Java 類,並將其命名為 RealmDatabase,並向其中新增以下程式碼。程式碼中添加了註釋以詳細瞭解。

package com.example.java_test_application;
import android.app.Application;
import io.realm.Realm;
public class RealmDatabase extends Application {
   @Override
   public void onCreate() {
      super.onCreate();
      // on below line we are initializing our real m database.
      Realm.init(this);
      // on below line we are creating a variable for realm configuration and initializing it.
      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 build method to generate the configurations.
         .build();
      // on below line we are setting the default
      // configuration to our realm database.
      Realm.setDefaultConfiguration(config);
   }
}

說明:在上面的程式碼中,我們正在初始化 Realm 資料庫並在 onCreate 方法中為其設定預設配置。

步驟 5:在 AndroidManifest.xml 檔案中定義此 RealmDatabase 類

導航到 app>AndroidManifest.xml 檔案,並在 application 標籤中新增以下行。

android:name=".RealmDatabase"

步驟 6:使用 activity_main.xml

導航到 activity_main.xml。如果此檔案不可見。要開啟此檔案。在左側窗格中導航到 app>res>layout>activity_main.xml 以開啟此檔案。開啟此檔案後。向其中新增以下程式碼。程式碼中添加了註釋以詳細瞭解。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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">

   <!-- on below line creating a text view for displaying the heading of our application -->
   <TextView
       android:id="@+id/idTVHeading"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_marginStart="10dp"
       android:layout_marginTop="100dp"
       android:layout_marginEnd="10dp"
       android:gravity="center"
       android:padding="4dp"
       android:text="Realm Database in Android"
       android:textAlignment="center"
       android:textColor="@color/black"
       android:textSize="20sp"
       android:textStyle="bold" />

   <!-- on below line creating edit text for name -->
   <EditText
       android:id="@+id/idEdtName"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_below="@id/idTVHeading"
       android:layout_margin="10dp"
       android:hint="Enter Name" />

   <!-- on below line creating edit text for age -->
   <EditText
       android:id="@+id/idEdtAge"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_below="@id/idEdtName"
       android:layout_margin="10dp"
       android:hint="Enter Age" />

   <!-- on below line creating a button for adding data -->
   <Button
       android:id="@+id/idBtnAddData"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_below="@id/idEdtAge"
       android:layout_margin="10dp"
       android:padding="4dp"
       android:text="Add Data to Database"
       android:textAllCaps="false" />
</RelativeLayout>

說明:在上面的程式碼中,我們建立了一個根佈局作為相對佈局。在此佈局中,我們建立了一個 TextView,用於顯示應用程式的標題。然後,我們建立了兩個 EditText 欄位,用於接收使用者的姓名和年齡輸入。之後,我們建立了一個按鈕,用於將資料新增到我們的 Realm 資料庫。

步驟 7:為我們的資料建立模型類

導航到 app>java>您的應用程式包名>右鍵單擊它>新建 Java 類,並將其命名為 DataObject,並向其中新增以下程式碼。程式碼中添加了註釋以詳細瞭解。

package com.example.java_test_application;
import io.realm.RealmObject;
import io.realm.annotations.PrimaryKey;
public class DataObject extends RealmObject{
   // on below line creating a long variable for id of each item of db which will be unique.
   @PrimaryKey
   private long id;
   // on below line creatig a variable for name and age.
   private String name;
   private String age;
   // on below line we are creating getter and setter methods for name and age variables.
   public String getName() {
       return name;
   }
   public void setName(String name) {
       this.name = name;
   }
   public String getAge() {
       return age;
   }
   public void setAge(String age) {
       this.age = age;
   }
   // on below line we are
   // creating an empty constructor for Data Object class..
   public DataObject() {
   }
}

說明:在上面的程式碼中,我們建立了三個變數,第一個是每個資料庫條目的 ID,然後建立了姓名和年齡的變數。之後,我們建立了一個空建構函式,最後為姓名和年齡變數建立了 getter 和 setter 方法。

步驟 8:使用 MainActivity.java 檔案

導航到 MainActivity.java。如果此檔案不可見。要開啟此檔案。在左側窗格中導航到 app>res>layout>MainActivity.java 以開啟此檔案。開啟此檔案後。向其中新增以下程式碼。程式碼中添加了註釋以詳細瞭解。

package com.example.java_test_application;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.StackView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.util.ArrayList;
import java.util.List;
import io.realm.gradle.Realm;
public class MainActivity extends AppCompatActivity {
   // creating variables for edit text on below line.
   private EditText nameEdt, ageEdt;
   // creating variable for button on below line.
   private Button addDataBtn;
   // on below line creating a variable for realm.
   private Realm realm;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);
       // initializing variables for edit text on below line.
       nameEdt = findViewById(R.id.idEdtName);
       ageEdt = findViewById(R.id.idEdtAge);
       // initializing variables for button on below line.
       addDataBtn = findViewById(R.id.idBtnAddData);
       // on below line initializing the variable for realm.
       realm = Realm.getDefaultInstance();
       // adding click listener for button on below line.
       addDataBtn.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View v) {
               // on below line validating if name and age is empty or not.
               if (nameEdt.getText().toString().isEmpty() && ageEdt.getText().toString().isEmpty()) {
                   // if both name and age is empty we are displaying a toast message on below line.
                   Toast.makeText(getApplicationContext(), "Please enter your name and age", Toast.LENGTH_SHORT).show();
               } else {
                   // name and age is not empty in thus case we are adding data to our database.
                   addDataToDB(nameEdt.getText().toString(), ageEdt.getText().toString());
                   // on below line displaying toast message as data has been added to database..
                   Toast.makeText(MainActivity.this, "Data has been added to database..", Toast.LENGTH_SHORT).show();
               }
           }
       });
   }
   private void addDataToDB(String name, String age) {
       // on below line creating and initializing our data object class
       DataObject dataObject = new DataObject();
       // on below line we are getting id for the course which we are storing.
       Number id = realm.where(DataObject.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 setting data for our modal class
       dataObject.setName(name);
       dataObject.setAge(age);
       // 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);
           }
       });
   }
}

說明:在上面的程式碼中,首先我們為 EditText、Button 和 Realm 資料庫建立變數。現在我們將看到 onCreate 方法。這是每個 Android 應用程式的預設方法。當應用程式檢視建立時,將呼叫此方法。在此方法中,我們設定內容檢視,即名為 activity_main.xml 的佈局檔案,以從該檔案中設定 UI。在 onCreate 方法中,我們使用我們在 activity_main.xml 檔案中給出的 ID 初始化按鈕和 EditText 變數。此外,我們還初始化 Realm 資料庫的變數。之後,我們為“新增資料”按鈕添加了一個點選監聽器。在點選監聽器方法中,我們首先驗證文字輸入欄位是否為空。我們檢查姓名和年齡 EditText 是否為空。如果兩者都為空,則顯示一條吐司訊息。在 else 條件中,我們只是呼叫 addDatatoDB 方法,該方法用於將資料新增到我們的 Realm 資料庫。

在 addDatatoDB 方法中,我們首先為 DataObject 建立和初始化變數。之後,我們建立一個數字,它將為我們提供 ID。然後,我們將 EditText 中的資料(如姓名和年齡)設定為我們的物件類變數。然後,我們呼叫一個 execute transition 方法,該方法用於將資料從應用程式新增到資料庫。最後,在按鈕的點選方法中,我們顯示一條吐司訊息,表示資料已新增到我們的資料庫。

新增上述程式碼後,現在我們只需單擊頂部的綠色圖示即可在移動裝置上執行我們的應用程式。

注意:確保您已連線到您的真實裝置或模擬器。

輸出

結論

在本文中,我們瞭解了什麼是 Realm 資料庫以及如何使用它在 Android 應用程式中儲存資料。

更新時間: 2023 年 5 月 9 日

3K+ 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.