# Introduction to the Realm SDK for Android

This is a beginner article where we introduce you to the Realm Android SDK, dive through its features, and illustrate development of the process with a demo application to get you started quickly.

In this article, you will learn how to set up an Android application with the Realm Android SDK, write basic queries to manipulate data, and you'll receive an introduction to Realm Studio, a tool designed to view the local Realm database.

>
>
>Pre-Requisites: You have created at least one app using Android Studio.
>
>

>
>
>**What is Realm?**
>
>Realm is an object database that is simple to embed in your mobile app.  Realm is a developer-friendly alternative to mobile databases such as SQLite and CoreData.
>
>

Before we start, create an Android application. Feel free to skip the step if you already have one.

**Step 0**: Open Android Studio and then select Create New Project. For more information, you can visit the official Android website.

Now, let's get started on how to add the Realm SDK to your application.

**Step 1**: Add the gradle dependency to the **project** level **build.gradle** file:

``` kotlin
dependencies {
   classpath "com.android.tools.build:gradle:$gradle_version"
   classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
   classpath "io.realm:realm-gradle-plugin:10.4.0" // add this line
}
```

Also, add **mavenCentral** as our dependency, which was previously **jCenter** for Realm 10.3.x and below.

``` kotlin
repositories {
   google()
   mavenCentral() // add this line
}
```

``` kotlin
allprojects {
    repositories {
        google()
        mavenCentral() // add this line
    }
}
```

**Step 2**: Add the Realm plugin to the **app** level **build.gradle** file:

``` kotlin
plugins {
   id 'com.android.application'
   id 'kotlin-android'
   id 'kotlin-kapt' // add this line
   id 'realm-android' // add this line
}
```

Keep in mind that order matters. You should add the **realm-android** plugin after **kotlin-kapt**.

We have completed setting up Realm in the project. Sync Gradle so that we can move to the next step.

**Step 3**: Initialize and create our first database:

The Realm SDK needs to be initialized before use. This can be done anywhere (application class, activity, or fragment) but to keep it simple, we recommend doing it in the application class.

``` kotlin
// Ready our SDK
Realm.init(this)
// Creating our db with custom properties
val config = RealmConfiguration.Builder()
   .name("test.db")
   .schemaVersion(1)
   .build()
Realm.setDefaultConfiguration(config)
```

Now that we have the Realm SDK added to our project, let's explore basic CRUD (Create, Read, Update, Delete) operations. To do this, we'll create a small application, building on MVVM design principles.

The application counts the number of times the app has been opened, which has been manipulated to give an illustration of CRUD operation.

1.  Create app view object when opened the first time — **C** R U D
2.  Read app viewed counts—C **R** U D
3.  Update app viewed counts—C R **U** D
4.  Delete app viewed counts— C R U **D**

    

Once you have a good understanding of the basic operations, then it is fairly simple to apply this to complex data transformation as, in the end, they are nothing but collections of CRUD operations.

Before we get down to the actual task, it's nice to have background knowledge on how Realm works. Realm is built to help developers avoid common pitfalls, like heavy lifting on the main thread, and follow best practices, like reactive programming.

The default configuration of the Realm allows programmers to read data on any thread and write only on the background thread. This configuration can be overwritten with:

``` kotlin
Realm.init(this)
val config = RealmConfiguration.Builder()
   .name("test.db")
   .allowQueriesOnUiThread(false)
   .schemaVersion(1)
   .deleteRealmIfMigrationNeeded()
   .build()
Realm.setDefaultConfiguration(config)
```

In this example, we keep `allowQueriesOnUiThread(true)` which is the default configuration.

Let's get started and create our object class `VisitInfo` which holds the visit count:

``` kotlin
open class VisitInfo : RealmObject() {

   @PrimaryKey
   var id = UUID.randomUUID().toString()

   var visitCount: Int = 0

}
```

In the above snippet, you will notice that we have extended the class with `RealmObject`, which allows us to directly save the object into the Realm.

We can insert it into the Realm like this:

``` kotlin
val db = Realm.getDefaultInstance()
db.executeTransactionAsync {
   val info = VisitInfo().apply {
       visitCount = count
   }
   it.insert(info)
}
```

To read the object, we write our query as:

``` kotlin
val db = Realm.getDefaultInstance()
val visitInfo = db.where(VisitInfo::class.java).findFirst()
```

To update the object, we use:

``` kotlin
val db = Realm.getDefaultInstance()
val visitInfo = db.where(VisitInfo::class.java).findFirst()

db.beginTransaction()
visitInfo.apply {
   visitCount += count
}

db.commitTransaction()
```

And finally, to delete the object:

``` kotlin
val visitInfo = db.where(VisitInfo::class.java).findFirst()
visitInfo?.deleteFromRealm()
```

So now, you will have figured out that it's very easy to perform any operation with Realm. You can also check out the Github repo for the complete application.

The next logical step is how to view data in the database. For that, let's introduce Realm Studio.

*Realm Studio is a developer tool for desktop operating systems that allows you to manage Realm database instances.*

Realm Studio is a very straightforward tool that helps you view your local Realm database file. You can install Realm Studio on any platform from .

Let's grab our database file from our emulator or real device.

Detailed steps are as follows:

**Step 1**: Go to Android Studio, open "Device File Explorer" from the right-side panel, and then select your emulator.

    

**Step 2**: Get the Realm file for our app. For this, open the folder named **data** as highlighted above, and then go to the **data** folder again. Next, look for the folder with your package name. Inside the **files** folder, look for the file named after the database you set up through the Realm SDK. In my case, it is **test.db**.

**Step 3**: To export, right-click on the file and select "Save As," and
then open the file in Realm Studio.

Notice the visit count in the `VisitInfo` class (AKA table) which is equivalent to the visit count of the application. That's all, folks.  Hope it helps to solve the last piece of the puzzle.

If you're an iOS developer, please check out Accessing Realm Data on iOS Using Realm Studio.

>
>
>If you have questions, please head to our developer community website where the MongoDB engineers and the MongoDB community will help you build your next big idea with MongoDB.
>
>