- Views: 1
- Report Article
- Articles
- Business & Careers
- Business Services
Realm Database
Posted: Jun 23, 2020
We provide mobile Application Development company services for every kind of business as fashion, wellness, shopping, E-commerce, and more. For many different reputed industries, we have created a dynamic, compelling, and user-friendly application for the Android platform.
Do you still end up being confused while attempting to
hold tables, compose queries, and perform the operations in the database?
If your response is yes, then Realm is the best way to explain it further we will follow a step-by-step process:-
1 Steps:
1.Introduction
2.Create Project in Android Studio
3.Add Realm IO Dependency
4.Create Model Class for Realm Database
5.Create Activity Which handles database operations
5.1- Insert Data Into Realm Database
5.2-Update Data Into Realm Database
5.3-Delete Data From Realm Database
2 Introduction :-Realm is a lightweight No-SQL database in Android based on cpp programming language.
Realm occupies very less memory space compared to SQLite. So ultimately it reduces the overall computation of our application also realm is very fast in reading & writing data as compared to SQLite.
Moreover,Realm is a cross platform database which enables to share your data over both Android&ios platforms,In Addition to that realm also has a database browser called realm browser which facilitates browsing your database easily.
Realm is not based on row-column structure, but it's based on Object tree.
Seems exciting right? So without wasting any time let’s dive deep into exploring realm database.
3 Configuring RealmNow to begin with firstly to configure realm modify your gradle build files as shown below:
1. Inside your app gradle simply use apply realm plugin below default android plugine.g:
apply plugin: 'com.android.application'
apply plugin: 'realm-android'
2.Go to your project gradle file and enter classpath of realm in your dependenciesclasspath 'com.android.tools.build:gradle:3.4.1'
classpath "io.realm:realm-gradle-plugin:5.10.0"
3.Now Sync your project and realm will be configured for your project. 4 Adding Realm Model ClassTo create model class, click on file>> new>> Java Class. Give appropriate name to this java file. I named it as Database.java. Model class must extend RealmObject/RealmModel class to use behaviour of Realm Database
Database.java:
Here as seen in image all realm Model classes should be annotated with @RealmClass or it will throw runtime exception. Moreover if your want any field to be primary key than annotate it with @Primarykey.
Now let’s explore Database operations step by step-
- Create a new empty activity
- Now Inside your oncreate of activity you need to initialize realm with:
Realm.init(this);
package com.example.realm;import io.realm.RealmModel; import io.realm.annotations.PrimaryKey; import io.realm.annotations.RealmClass;
@RealmClass public class Database implements RealmModel { @PrimaryKey Integer id=null;
String name=null;
String address=null;
String phonenumber=null;
Boolean status=false;
public Integer getId() { return id; }
public void setId(Integer id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getAddress() { return address; }
public void setAddress(String address) { this.address = address; }
public String getPhonenumber() { return phonenumber; }
public void setPhonenumber(String phonenumber) { this.phonenumber = phonenumber; }
public Boolean getStatus() { return status; }
public void setStatus(Boolean status) { this.status = status; }
} view raw gistfile1.txt hosted with? by GitHub 5 Custom Configuration
Attributing onto that you can also set a custom configuration to realm with this code:
All of this initialization is to be done only once per application.
3- Now to start writing and reading data from database follow these steps:
1. Take a realm object in your activity eg:-
static Realm realm = null;
2. Now you need to initialize that realm object with this:
realm = Realm.getDefaultInstance();
RealmConfiguration realmConfiguration = new RealmConfiguration.Builder().name("RealmDatabase.realm").schemaVersion(1).deleteRealmIfMigrationNeeded().build(); Realm.getInstance(realmConfiguration); Realm.setDefaultConfiguration(realmConfiguration); view raw gistfile1.txt hosted with? by GitHub 6 Insert OperationNow to Perform a normal insert operation into database look at this code:
public void normalinserttransaction(){ realm = Realm.getDefaultInstance(); //Here We Are initializing our realm object realm.executeTransaction(new Realm.Transaction() { @Override public void execute(Realm realm) { //This is the overridden method which allows to perform entries into database Number currentIdNum = realm.where(Database.class).max("id"); //take maximum present primarykey value int nextId; if(currentIdNum == null) { nextId = 1; //Set default key value if no key is present } else { nextId = currentIdNum.intValue() + 1; //Logic to increment primary key } //When Using a primary key in database we must specify a primary key while creating a realm object to perform entry into database if not specified it will throw runtime exception Database db = realm.createObject(Database.class,nextId); //Here Database is our realm model class and by doing realm.create object we’re create new entry for database db.setName(name.getText().toString()); //take database object and set your field values db.setAddress(address.getText().toString()); db.setPhonenumber(number.getText().toString()); Toast.makeText(MainActivity.this,"Okay Data Saved",Toast.LENGTH_LONG).show(); } }); } view raw gistfile1.txt hosted with? by GitHub 7 Realm Async TransactionNow if you want to listen for success and failures on database operations you can do that with realm async transaction.
public void asynctransaction(){ realm.executeTransactionAsync(new Realm.Transaction() { @Override public void execute(Realm realm) { Database db = realm.createObject(Database.class); db.setName(name.getText().toString()); db.setAddress(address.getText().toString()); db.setPhonenumber(number.getText().toString()); } }, new Realm.Transaction.OnSuccess() {
@Override public void onSuccess() { //Database operation completed successfully
} }, new Realm.Transaction.OnError() { @Override public void onError(Throwable error) { //Error Handling while executing Database Operation
} }
); } view raw gistfile1.txt hosted with? by GitHub 8 Read Data
To Read Data from database take a look at below code:
public void readsinglevalue(){ Database db = realm.where(Database.class).equalTo("id",Integer.parseInt(id.getText().toString())).findFirst(); //This is a realm query with fetches our data with specified condition if (db!=null) { String name = db.getName(); //get field data String address = db.getAddress(); String number = db.getPhonenumber(); tvdata.setText(name+"\n"+number+"\n"+address); } } view raw gistfile1.txt hosted with? by GitHub 9 Update DataNow to Update data into database follow this example:
public void updateonid(){ realm = Realm.getDefaultInstance(); //get realm instance realm.executeTransaction(new Realm.Transaction() { @Override public void execute(Realm realm) { Database db = realm.where(Database.class).equalTo("id",Integer.parseInt(id.getText().toString())).findFirst(); //specify our realm query //Note always take your query object while trying to update else it won’t work if try to create new objects if (db!=null) //Now if data is found { db.setName(name.getText().toString()); //Update at specified query data db.setAddress(address.getText().toString()); db.setPhonenumber(number.getText().toString()); } } }); } view raw gistfile1.txt hosted with? by GitHub 10 Fetch DataLastly, if you want to fetch all entries of a realm database into a single arraylist structure you can do this-
RealmResults results = realm.where(Database.class).equalTo("id",Integer.parseInt(id.getText().toString())).findAll(); view raw gistfile1.txt hosted with? by GitHub 11 Edit - Delete Or DropHere RealmResults is just a simple model arraylist from which you can fetch data just like a simple arraylist but it has one limitation at runtime if you want to delete or drop its data at specific position you are not allowed to do that so to solve that you can copy that realm results list into another list and then edit that other list.
E.g:-
public List getModelList() { List list = new ArrayList(); Realm realm = null; try { realm = Realm.getDefaultInstance(); RealmResults results = realm.where(Database.class).findAll(); list.addAll(realm.copyFromRealm(results)); } finally { if (realm!= null) { realm.close(); } } return list; }List = getmodellist() //now you can edit your new list view raw gistfile1.txt hosted with? by GitHub 12 Activity Code package com.example.realm;
import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast;
import java.util.ArrayList; import java.util.List;
import io.realm.Realm; import io.realm.RealmConfiguration; import io.realm.RealmResults;
public class MainActivity extends AppCompatActivity {
static Realm realm = null; EditText name,address,number,id; Button save,read,upate; TextView tvdata; public static List arrayList = new ArrayList(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //Initialize Realm Realm.init(this); //Set custom configuration to realm RealmConfiguration realmConfiguration = new RealmConfiguration.Builder().name("RealmDatabase.realm").schemaVersion(1).deleteRealmIfMigrationNeeded().build(); Realm.getInstance(realmConfiguration); Realm.setDefaultConfiguration(realmConfiguration);
//assign realminstance realm = Realm.getDefaultInstance(); //view binding name = findViewById(R.id.name); address = findViewById(R.id.Address); number = findViewById(R.id.Phonenumber); save = findViewById(R.id.save); id = findViewById(R.id.id); read = findViewById(R.id.read); upate = findViewById(R.id.update); tvdata = findViewById(R.id.tvdata); read.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { readsinglevalue(); } }); save.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { normalinserttransaction(); } }); upate.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { updateonid(); } });
//clone realm results to an arraylist for run time manipulation arrayList = getModelList(); } public void updateonid(){ realm = Realm.getDefaultInstance(); realm.executeTransaction(new Realm.Transaction() { @Override public void execute(Realm realm) { Database db = realm.where(Database.class).equalTo("id",Integer.parseInt(id.getText().toString())).findFirst(); if (db!=null) { db.setName(name.getText().toString()); db.setAddress(address.getText().toString()); db.setPhonenumber(number.getText().toString()); } } }); } public void readsinglevalue(){ Database db = realm.where(Database.class).equalTo("id",Integer.parseInt(id.getText().toString())).findFirst(); RealmResults results = realm.where(Database.class).equalTo("id",Integer.parseInt(id.getText().toString())).findAll(); if (db!=null) { String name = db.getName(); String address = db.getAddress(); String number = db.getPhonenumber(); tvdata.setText(name+"\n"+number+"\n"+address); } } public void normalinserttransaction(){ realm = Realm.getDefaultInstance(); realm.executeTransaction(new Realm.Transaction() { @Override public void execute(Realm realm) { Number currentIdNum = realm.where(Database.class).max("id"); int nextId; if(currentIdNum == null) { nextId = 1; } else { nextId = currentIdNum.intValue() + 1; } Database db = realm.createObject(Database.class,nextId); db.setName(name.getText().toString()); db.setAddress(address.getText().toString()); db.setPhonenumber(number.getText().toString()); Toast.makeText(MainActivity.this,"Okay Data Saved",Toast.LENGTH_LONG).show(); } }); }
public void asynctransaction(){ realm.executeTransactionAsync(new Realm.Transaction() { @Override public void execute(Realm realm) { Database db = realm.createObject(Database.class); db.setName(name.getText().toString()); db.setAddress(address.getText().toString()); db.setPhonenumber(number.getText().toString()); } }, new Realm.Transaction.OnSuccess() {
@Override public void onSuccess() { //Database operation completed successfully
} }, new Realm.Transaction.OnError() { @Override public void onError(Throwable error) { //Error Handling while executing Database Operation
} }
); } public List getModelList() { List list = new ArrayList(); Realm realm = null; try { realm = Realm.getDefaultInstance(); RealmResults results = realm.where(Database.class).findAll(); list.addAll(realm.copyFromRealm(results)); } finally { if (realm!= null) { realm.close(); } } return list; } }
view raw gistfile1.txt hosted with? by GitHub
About the Author
Vasundhara Infotech is Best Unity Game, Custom Web Design, iOS, Android Application Development, & Seo Type IT Services Provider Company in Surat, India - Usa.