📌  相关文章
📜  如何在Android中安装数据并将其添加到Realm数据库?

📅  最后修改于: 2021-05-10 16:23:02             🧑  作者: Mango

领域数据库是MongoDb提供的一项服务,用于在本地用户设备中存储数据。借助此数据,可以轻松地将数据存储在用户的设备中,并且可以轻松地对其进行访问。我们可以使用该数据库将数据存储在用户设备本身中。这是一系列4篇文章的系列文章,我们将在其中使用Android的Realm Database执行基本的CRUD(创建,读取,更新和删除)操作。我们将在本系列中涵盖以下4篇文章:

  1. 如何在Android中安装数据并将其添加到Realm数据库?
  2. 如何从Android中的Realm数据库读取数据?
  3. 如何在Android中将数据更新到Realm数据库?
  4. 如何在Android的Realm数据库中删除数据?

在本文中,我们将介绍如何在Android中将数据安装和添加到Realm数据库。

如何将数据存储在Realm数据库中?

数据以表的形式存储在Realm数据库中。当我们将这些数据存储在Realm数据库中时,它以类似于Excel工作表的表格的形式排列。下面是存储在Realm数据库中的Realm数据库的表示。

我们将在本文中构建什么?

我们将构建一个简单的应用程序,在其中将数据添加到Realm数据库中。我们将创建一个数据库,用于添加课程名称,课程说明和课程持续时间。我们将所有这些数据保存在我们的Realm数据库中。下面提供了一个示例视频,以使您对本文中的工作有个大概的了解。注意,我们将使用Java语言实现该项目。

分步实施

步骤1:创建一个新项目

要在Android Studio中创建新项目,请参阅如何在Android Studio中创建/启动新项目。请注意,选择Java作为编程语言。

步骤2:在项目级别的build.gradle文件的“依赖关系”部分中添加依赖关系

导航至应用程序> Gradle脚本> build.gradle(项目),然后在“依赖项”部分添加类路径依赖项。您可以在以下部分中查看依赖性。

dependencies {
        classpath "com.android.tools.build:gradle:4.1.2"
        
        // add below dependancy
        classpath "io.realm:realm-gradle-plugin:10.3.1"

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
}

添加后,现在导航到build.gradle(Module)并将以下代码添加到其中。在此文件顶部添加插件。

apply plugin: 'realm-android'     

之后,在dependencies部分上方添加以下代码。

realm {
    syncEnabled = true
}

现在同步您的项目,现在我们将着手创建一个新的Java类。以下是build.gradle(模块)文件的完整代码:

Java
plugins {
    id 'com.android.application'
}
 
apply plugin: 'realm-android'
 
android {
    compileSdkVersion 30
    buildToolsVersion "30.0.3"
    ndkVersion '21.3.6528147'
 
    defaultConfig {
        applicationId "com.example.realm"
        minSdkVersion 23
        targetSdkVersion 30
        versionCode 1
        versionName "1.0"
 
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
 
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}
 
realm {
    syncEnabled = true
}
 
dependencies {
    implementation 'androidx.appcompat:appcompat:1.2.0'
    implementation 'com.google.android.material:material:1.3.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
    testImplementation 'junit:junit:4.+'
    androidTestImplementation 'androidx.test.ext:junit:1.1.2'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
}


Java
import android.app.Application;
 
import io.realm.Realm;
import io.realm.RealmConfiguration;
 
public class RealmDb extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
         
        // on below line we are
        // initializing our realm database.
        Realm.init(this);
         
        // on below line we are setting realm configuration
        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 method to build.
                        .build();
        // on below line we are setting
        // configuration to our realm database.
        Realm.setDefaultConfiguration(config);
    }
}


XML


 
    
    
 
    
    
 
    
    
 
    
    
 
    
    


Java
import io.realm.RealmObject;
import io.realm.annotations.PrimaryKey;
 
public class DataModal extends RealmObject {
    // on below line we are creating our variables
    // and with are using primary key for our id.
    @PrimaryKey
    private long id;
    private String courseName;
    private String courseDescription;
    private String courseTracks;
    private String courseDuration;
 
    // on below line we are
    // creating an empty constructor.
    public DataModal() {
    }
 
    // below line we are
    // creating getter and setters.
    public String getCourseTracks() {
        return courseTracks;
    }
 
    public void setCourseTracks(String courseTracks) {
        this.courseTracks = courseTracks;
    }
 
    public long getId() {
        return id;
    }
 
    public void setId(long id) {
        this.id = id;
    }
 
    public String getCourseName() {
        return courseName;
    }
 
    public void setCourseName(String courseName) {
        this.courseName = courseName;
    }
 
    public String getCourseDescription() {
        return courseDescription;
    }
 
    public void setCourseDescription(String courseDescription) {
        this.courseDescription = courseDescription;
    }
 
    public String getCourseDuration() {
        return courseDuration;
    }
 
    public void setCourseDuration(String courseDuration) {
        this.courseDuration = courseDuration;
    }
}


Java
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
 
import androidx.appcompat.app.AppCompatActivity;
 
import io.realm.Realm;
 
public class MainActivity extends AppCompatActivity {
 
    // creating variables for our edit text
    private EditText courseNameEdt, courseDurationEdt, courseDescriptionEdt, courseTracksEdt;
    private Realm realm;
     
    // creating a strings for storing
    // our values from edittext fields.
    private String courseName, courseDuration, courseDescription, courseTracks;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
         
        // initializing our edittext and buttons
        realm = Realm.getDefaultInstance();
        courseNameEdt = findViewById(R.id.idEdtCourseName);
        courseDescriptionEdt = findViewById(R.id.idEdtCourseDescription);
        courseDurationEdt = findViewById(R.id.idEdtCourseDuration);
         
        // creating variable for button
        Button submitCourseBtn = findViewById(R.id.idBtnAddCourse);
        courseTracksEdt = findViewById(R.id.idEdtCourseTracks);
        submitCourseBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                 
                // getting data from edittext fields.
                courseName = courseNameEdt.getText().toString();
                courseDescription = courseDescriptionEdt.getText().toString();
                courseDuration = courseDurationEdt.getText().toString();
                courseTracks = courseTracksEdt.getText().toString();
                 
                // validating the text fields if empty or not.
                if (TextUtils.isEmpty(courseName)) {
                    courseNameEdt.setError("Please enter Course Name");
                } else if (TextUtils.isEmpty(courseDescription)) {
                    courseDescriptionEdt.setError("Please enter Course Description");
                } else if (TextUtils.isEmpty(courseDuration)) {
                    courseDurationEdt.setError("Please enter Course Duration");
                } else if (TextUtils.isEmpty(courseTracks)) {
                    courseTracksEdt.setError("Please enter Course Tracks");
                } else {
                    // calling method to add data to Realm database..
                    addDataToDatabase(courseName, courseDescription, courseDuration, courseTracks);
                    Toast.makeText(MainActivity.this, "Course added to database..", Toast.LENGTH_SHORT).show();
                    courseNameEdt.setText("");
                    courseDescriptionEdt.setText("");
                    courseDurationEdt.setText("");
                    courseTracksEdt.setText("");
                }
            }
        });
    }
 
    private void addDataToDatabase(String courseName, String courseDescription, String courseDuration, String courseTracks) {
         
        // on below line we are creating
        // a variable for our modal class.
        DataModal modal = new DataModal();
         
        // on below line we are getting id for the course which we are storing.
        Number id = realm.where(DataModal.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 we are setting the
        // data entered by user in our modal class.
        modal.setId(nextId);
        modal.setCourseDescription(courseDescription);
        modal.setCourseName(courseName);
        modal.setCourseDuration(courseDuration);
        modal.setCourseTracks(courseTracks);
         
        // 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);
            }
        });
    }
}


步骤3:创建新的Java类以初始化realmDatabase

导航到应用程序> Java >应用程序的程序包名称>右键单击它>新建> Java类,并将其命名为RealmDb,然后将以下代码添加到其中。

Java

import android.app.Application;
 
import io.realm.Realm;
import io.realm.RealmConfiguration;
 
public class RealmDb extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
         
        // on below line we are
        // initializing our realm database.
        Realm.init(this);
         
        // on below line we are setting realm configuration
        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 method to build.
                        .build();
        // on below line we are setting
        // configuration to our realm database.
        Realm.setDefaultConfiguration(config);
    }
}

步骤4:在AndroidManifest.xml文件中定义此类

导航到app> AndroidManifest.xml文件,并在标记内添加以下行。

现在,我们将继续使用activity_main.xml。

步骤5:使用activity_main.xml文件

导航到应用程序> res>布局> activity_main.xml,然后将以下代码添加到该文件中。以下是activity_main.xml文件的代码。

XML格式



 
    
    
 
    
    
 
    
    
 
    
    
 
    
    

第6步:创建用于存储数据的模式类

导航到应用程序> Java >应用程序的程序包名称>右键单击它>新建> Java类,并将其命名为DataModal,然后将以下代码添加到其中。

Java

import io.realm.RealmObject;
import io.realm.annotations.PrimaryKey;
 
public class DataModal extends RealmObject {
    // on below line we are creating our variables
    // and with are using primary key for our id.
    @PrimaryKey
    private long id;
    private String courseName;
    private String courseDescription;
    private String courseTracks;
    private String courseDuration;
 
    // on below line we are
    // creating an empty constructor.
    public DataModal() {
    }
 
    // below line we are
    // creating getter and setters.
    public String getCourseTracks() {
        return courseTracks;
    }
 
    public void setCourseTracks(String courseTracks) {
        this.courseTracks = courseTracks;
    }
 
    public long getId() {
        return id;
    }
 
    public void setId(long id) {
        this.id = id;
    }
 
    public String getCourseName() {
        return courseName;
    }
 
    public void setCourseName(String courseName) {
        this.courseName = courseName;
    }
 
    public String getCourseDescription() {
        return courseDescription;
    }
 
    public void setCourseDescription(String courseDescription) {
        this.courseDescription = courseDescription;
    }
 
    public String getCourseDuration() {
        return courseDuration;
    }
 
    public void setCourseDuration(String courseDuration) {
        this.courseDuration = courseDuration;
    }
}

步骤7:使用MainActivity。 Java文件

转到MainActivity。 Java文件并参考以下代码。下面是MainActivity的代码。 Java文件。在代码内部添加了注释,以更详细地了解代码。

Java

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
 
import androidx.appcompat.app.AppCompatActivity;
 
import io.realm.Realm;
 
public class MainActivity extends AppCompatActivity {
 
    // creating variables for our edit text
    private EditText courseNameEdt, courseDurationEdt, courseDescriptionEdt, courseTracksEdt;
    private Realm realm;
     
    // creating a strings for storing
    // our values from edittext fields.
    private String courseName, courseDuration, courseDescription, courseTracks;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
         
        // initializing our edittext and buttons
        realm = Realm.getDefaultInstance();
        courseNameEdt = findViewById(R.id.idEdtCourseName);
        courseDescriptionEdt = findViewById(R.id.idEdtCourseDescription);
        courseDurationEdt = findViewById(R.id.idEdtCourseDuration);
         
        // creating variable for button
        Button submitCourseBtn = findViewById(R.id.idBtnAddCourse);
        courseTracksEdt = findViewById(R.id.idEdtCourseTracks);
        submitCourseBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                 
                // getting data from edittext fields.
                courseName = courseNameEdt.getText().toString();
                courseDescription = courseDescriptionEdt.getText().toString();
                courseDuration = courseDurationEdt.getText().toString();
                courseTracks = courseTracksEdt.getText().toString();
                 
                // validating the text fields if empty or not.
                if (TextUtils.isEmpty(courseName)) {
                    courseNameEdt.setError("Please enter Course Name");
                } else if (TextUtils.isEmpty(courseDescription)) {
                    courseDescriptionEdt.setError("Please enter Course Description");
                } else if (TextUtils.isEmpty(courseDuration)) {
                    courseDurationEdt.setError("Please enter Course Duration");
                } else if (TextUtils.isEmpty(courseTracks)) {
                    courseTracksEdt.setError("Please enter Course Tracks");
                } else {
                    // calling method to add data to Realm database..
                    addDataToDatabase(courseName, courseDescription, courseDuration, courseTracks);
                    Toast.makeText(MainActivity.this, "Course added to database..", Toast.LENGTH_SHORT).show();
                    courseNameEdt.setText("");
                    courseDescriptionEdt.setText("");
                    courseDurationEdt.setText("");
                    courseTracksEdt.setText("");
                }
            }
        });
    }
 
    private void addDataToDatabase(String courseName, String courseDescription, String courseDuration, String courseTracks) {
         
        // on below line we are creating
        // a variable for our modal class.
        DataModal modal = new DataModal();
         
        // on below line we are getting id for the course which we are storing.
        Number id = realm.where(DataModal.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 we are setting the
        // data entered by user in our modal class.
        modal.setId(nextId);
        modal.setCourseDescription(courseDescription);
        modal.setCourseName(courseName);
        modal.setCourseDuration(courseDuration);
        modal.setCourseTracks(courseTracks);
         
        // 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中输入所需的数据。最重要的是,如果您想了解如何在Android Studio中查看和查找领域数据库,请参考本文您将在下面看到这是如何在Realm数据库中存储数据的。

以下是执行安装和添加操作后的完整项目文件结构: