How to Upload Data Packs on Realms Java

Realm Database is a service which is provided by MongoDb which is used to shop information in users device locally. With the assistance of this data tin can be stored hands in users' devices and can be accessed easily. Nosotros tin can use this database to store data in the user's device itself. This is a serial of iv manufactures in which we are going to perform the basic Grime (Create, Read, Update, and Delete) operation with Realm Database in Android. We are going to cover the following iv manufactures in this series:

  1. How to Install and Add Data to Realm Database in Android?
  2. How to Read Data from Realm Database in Android?
  3. How to Update Data to Realm Database in Android?
  4. How to Delete Data in Realm Database in Android?

In this article, we volition take a await at installing and calculation data to the Realm Database in Android.

How Data is existence stored in the Realm database?

Data is stored in the Realm database in the class of tables. When we stored this information in our Realm database it is arranged in the grade of tables that are like to that of an Excel sheet. Below is the representation of our Realm database which we are storing in our Realm database.

What we are going to build in this article?

Nosotros volition be building a uncomplicated application in which we will exist adding information to the Realm database. We will exist creating a database for calculation form names, form descriptions, and course duration. We will exist saving all this information in our Realm database. A sample video is given beneath to go an idea about what nosotros are going to do in this article. Note that we are going to implement this project using the Java language.

Stride by Step Implementation

Step 1: Create a New Project

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Annotation that select Java every bit the programming language.

Pace 2: Calculation dependency in the dependencies section in the project-level build.gradle file

Navigate to the app > Gradle Scripts > build.gradle (Project) and add together classpath dependency in the dependencies section. You can go to see dependency in the beneath department.

dependencies {         classpath "com.android.tools.build:gradle:4.1.2"                  // add together beneath dependency         classpath "io.realm:realm-gradle-plugin:x.iii.one"          // Note: Practise non place your application dependencies here; they belong         // in the individual module build.gradle files }

Later on adding this now navigates to build.gradle (Module) and add the beneath code to it. Add together plugin on top of this file.

apply plugin: 'realm-android'        

Later on that add together the below code to a higher place the dependencies section.

realm {     syncEnabled = true }

Now sync your project, and now we volition move towards creating a new coffee class. Below is the complete code for the build.gradle (Module) file:

Coffee

plugins {

id 'com.android.application'

}

use plugin: 'realm-android'

android {

compileSdkVersion 30

buildToolsVersion "thirty.0.3"

ndkVersion '21.3.6528147'

defaultConfig {

applicationId "com.case.realm"

minSdkVersion 23

targetSdkVersion thirty

versionCode 1

versionName "ane.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 = truthful

}

dependencies {

implementation 'androidx.appcompat:appcompat:1.2.0'

implementation 'com.google.android.material:material:1.iii.0'

implementation 'androidx.constraintlayout:constraintlayout:ii.0.4'

testImplementation 'junit:junit:4.+'

androidTestImplementation 'androidx.examination.ext:junit:1.i.2'

androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'

}

Stride 3: Creating a new java class for initializing the realmDatabase

Navigate to the app > coffee > your app'due south package name > Right-click on information technology > New > Java class and name it as RealmDb and add the below code to it.

Java

import android.app.Application;

import io.realm.Realm;

import io.realm.RealmConfiguration;

public class RealmDb extends Awarding {

@Override

public void onCreate() {

super .onCreate();

Realm.init( this );

RealmConfiguration config =

new RealmConfiguration.Architect()

.allowWritesOnUiThread( true )

.deleteRealmIfMigrationNeeded()

.build();

Realm.setDefaultConfiguration(config);

}

}

Footstep four: Defining this class in the AndroidManifest.xml file

Navigate to the app > AndroidManifest.xml file and inside the <awarding> tag add the below line.

android:name=".RealmDb"

Now we volition move towards working with activity_main.xml.

Pace 5: Working with the activity_main.xml file

Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.

XML

<? xml version = "one.0" encoding = "utf-8" ?>

< LinearLayout

android:layout_width = "match_parent"

android:layout_height = "match_parent"

android:orientation = "vertical"

tools:context = ".MainActivity" >

< EditText

android:id = "@+id/idEdtCourseName"

android:layout_width = "match_parent"

android:layout_height = "wrap_content"

android:layout_margin = "10dp"

android:hint = "Enter course Name" />

< EditText

android:id = "@+id/idEdtCourseDuration"

android:layout_width = "match_parent"

android:layout_height = "wrap_content"

android:layout_margin = "10dp"

android:hint = "Enter Grade Duration" />

< EditText

android:id = "@+id/idEdtCourseTracks"

android:layout_width = "match_parent"

android:layout_height = "wrap_content"

android:layout_margin = "10dp"

android:hint = "Enter Course Tracks" />

< EditText

android:id = "@+id/idEdtCourseDescription"

android:layout_width = "match_parent"

android:layout_height = "wrap_content"

android:layout_margin = "10dp"

android:hint = "Enter Course Description" />

< Button

android:id = "@+id/idBtnAddCourse"

android:layout_width = "match_parent"

android:layout_height = "wrap_content"

android:layout_margin = "10dp"

android:text = "Add Course"

android:textAllCaps = "false" />

</ LinearLayout >

Step 6: Creating a modal class for storing our data

Navigate to the app > coffee > your app'south package name > Correct-click on it > New > Java course and name it as DataModal and add together the beneath code to it.

Java

import io.realm.RealmObject;

import io.realm.annotations.PrimaryKey;

public grade DataModal extends RealmObject {

@PrimaryKey

private long id;

private String courseName;

private String courseDescription;

individual Cord courseTracks;

private String courseDuration;

public DataModal() {

}

public Cord getCourseTracks() {

render 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(Cord courseName) {

this .courseName = courseName;

}

public String getCourseDescription() {

return courseDescription;

}

public void setCourseDescription(String courseDescription) {

this .courseDescription = courseDescription;

}

public String getCourseDuration() {

render courseDuration;

}

public void setCourseDuration(String courseDuration) {

this .courseDuration = courseDuration;

}

}

Step 7: Working with the MainActivity.java file

Become to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added within the code to understand the code in more detail.

Java

import android.os.Bundle;

import android.text.TextUtils;

import android.view.View;

import android.widget.Push;

import android.widget.EditText;

import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import io.realm.Realm;

public class MainActivity extends AppCompatActivity {

private EditText courseNameEdt, courseDurationEdt, courseDescriptionEdt, courseTracksEdt;

private Realm realm;

individual String courseName, courseDuration, courseDescription, courseTracks;

@Override

protected void onCreate(Bundle savedInstanceState) {

super .onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

realm = Realm.getDefaultInstance();

courseNameEdt = findViewById(R.id.idEdtCourseName);

courseDescriptionEdt = findViewById(R.id.idEdtCourseDescription);

courseDurationEdt = findViewById(R.id.idEdtCourseDuration);

Push button submitCourseBtn = findViewById(R.id.idBtnAddCourse);

courseTracksEdt = findViewById(R.id.idEdtCourseTracks);

submitCourseBtn.setOnClickListener( new View.OnClickListener() {

@Override

public void onClick(View v) {

courseName = courseNameEdt.getText().toString();

courseDescription = courseDescriptionEdt.getText().toString();

courseDuration = courseDurationEdt.getText().toString();

courseTracks = courseTracksEdt.getText().toString();

if (TextUtils.isEmpty(courseName)) {

courseNameEdt.setError( "Please enter Form Proper name" );

} else if (TextUtils.isEmpty(courseDescription)) {

courseDescriptionEdt.setError( "Please enter Course Description" );

} else if (TextUtils.isEmpty(courseDuration)) {

courseDurationEdt.setError( "Please enter Form Elapsing" );

} else if (TextUtils.isEmpty(courseTracks)) {

courseTracksEdt.setError( "Please enter Grade Tracks" );

} else {

addDataToDatabase(courseName, courseDescription, courseDuration, courseTracks);

Toast.makeText(MainActivity. this , "Course added to database.." , Toast.LENGTH_SHORT).bear witness();

courseNameEdt.setText( "" );

courseDescriptionEdt.setText( "" );

courseDurationEdt.setText( "" );

courseTracksEdt.setText( "" );

}

}

});

}

private void addDataToDatabase(String courseName, String courseDescription, String courseDuration, String courseTracks) {

DataModal modal = new DataModal();

Number id = realm.where(DataModal. class ).max( "id" );

long nextId;

if (id == null ) {

nextId = 1 ;

} else {

nextId = id.intValue() + i ;

}

modal.setId(nextId);

modal.setCourseDescription(courseDescription);

modal.setCourseName(courseName);

modal.setCourseDuration(courseDuration);

modal.setCourseTracks(courseTracks);

realm.executeTransaction( new Realm.Transaction() {

@Override

public void execute(Realm realm) {

realm.copyToRealm(modal);

}

});

}

}

Now run your app and see the output of the app. In this article, you will just able to add together the data to our database. In the side by side article, we will take a expect at reading this data.

Output:

After successfully executed the code enter the required information inside the EditText. Most importantly if you want to know How to View and Locate the Realm Database in Android Studio and so delight refer to this article . And yous tin can see below this is how the information stored in the Realm database.

Below is the complete project file structure later performing the installation and add operation:


doresamen1971.blogspot.com

Source: https://www.geeksforgeeks.org/how-to-install-and-add-data-to-realm-database-in-android/

0 Response to "How to Upload Data Packs on Realms Java"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel