[Android] Uses Realm database on Kotlin Language

This article I would like to show how to use Realm database on Kotlin language.

What is Realm ? click

How to install Realm database to Android project ? click and scroll to Installation part.

What is Kotlin Language ? click

How to implement Kotlin to project ? click

For this article I had created a simple Android app to add or delete Students data and show raw data after added or deleted by using Realm database to store student data and Kotlin is the language for this project.


First step. Created Android project and implement Kotlin to the project.

Next step. implement Realm database to project.

Next step. Created customise application class like below code.

//MyApp.java
package com.example.kornsinmac.kotrealm

import android.app.Application
import io.realm.Realm
import io.realm.RealmConfiguration

/**
* Created by kornsin.mac on 4/17/2016 AD.
*/
class MyApp : Application() {
override fun onCreate() {
super.onCreate()
var c = RealmConfiguration.Builder(applicationContext)
c.name("student")
c.deleteRealmIfMigrationNeeded()
Realm.setDefaultConfiguration(c.build())
}
}
--------------------------------------------------------------------


AndroidManifest.xml

<!-- AndroidManifest.xml -->
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.kornsinmac.kotrealm">

<application
android:name=".MyApp"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:largeHeap="true"
android:theme="@style/AppTheme">
<activity android:name=".activities.MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

</manifest>

Next step. Created object for Student data and inherit RealmObject like below.

//Student.java
package com.example.kornsinmac.kotrealm.entities

import io.realm.RealmObject
import io.realm.annotations.PrimaryKey

/**
* Created by kornsin.mac on 4/17/2016 AD.
*/
open class Student(
@PrimaryKey open var _ID: Int = 0,
open var stuSex: Boolean = false,
open var firstName: String = "",
open var lastName: String = "",
open var stuClass: Int = 0
)
: RealmObject() {

fun copy(
_ID: Int = this._ID,
stuSex: Boolean = this.stuSex,
firstName: String = this.firstName,
lastName: String = this.lastName,
stuClass: Int = this.stuClass)
= Student(_ID, stuSex, firstName, lastName, stuClass)
}

“The open annotation on a class is the opposite of Java’s final: it allows others to inherit from this class. By default, all classes in Kotlin are final, which corresponds to Effective Java, Item 17: Design and document for inheritance or else prohibit it.” [https://kotlinlang.org/docs/reference/classes.html]


Next step. Created simple Student Interface.

package com.example.kornsinmac.kotrealm.dataInterface

import com.example.kornsinmac.kotrealm.entities.Student
import io.realm.Realm

/**
* Created by kornsin.mac on 4/17/2016 AD.
*/
interface StudentInterface {
fun addStudent(realm: Realm, student: Student): Boolean
fun delStudent(realm: Realm, _ID: Int): Boolean
fun editStudent(realm: Realm, student: Student): Boolean
fun getStudent(realm: Realm, studentId: Int): Student
fun removeLastStudent(realm: Realm)
}

Next step. Created Student Model and its implement StudentInterface.java

//StudentModel.java
package com.example.kornsinmac.kotrealm.model

import com.example.kornsinmac.kotrealm.dataInterface.StudentInterface
import com.example.kornsinmac.kotrealm.entities.Student
import io.realm.Realm
import io.realm.RealmResults

/**
* Created by kornsin.mac on 4/17/2016 AD.
*/
class StudentModel : StudentInterface {
override fun removeLastStudent(realm: Realm) {
realm.beginTransaction()
getLastStudent(realm).removeFromRealm()
realm.commitTransaction()
}

override fun addStudent(realm: Realm, student: Student): Boolean {
try {
realm.beginTransaction()
realm.copyToRealmOrUpdate(student)
realm.commitTransaction()
return true
} catch (e: Exception) {
println(e)
return false
}
}

override fun delStudent(realm: Realm, _ID: Int): Boolean {
try {
realm.beginTransaction()
realm.where(Student :: class.java).equalTo("_ID", _ID).findFirst().removeFromRealm()
realm.commitTransaction()
return true
} catch (e: Exception) {
println(e)
return false
}
}

override fun editStudent(realm: Realm, student: Student): Boolean {
try {
realm.beginTransaction()
realm.copyToRealm(student)
realm.commitTransaction()
return true
} catch (e: Exception) {
println(e)
return false
}
}

override fun getStudent(realm: Realm, studentId: Int): Student {
return realm.where(Student::class.java).equalTo("_ID", studentId).findFirst()
}

fun getLastStudent(realm: Realm): Student {
return realm.where(Student::class.java).findAll().last()
}

fun getStudents(realm: Realm): RealmResults<Student> {
return realm.where(Student::class.java).findAll()
}

}

Next step. Created layout for Add Delete and Show student data, the result like title image.

<!-- main_activity.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:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".activities.MainActivity">

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add Student"
android:id="@+id/add_button"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Delete Student"
android:id="@+id/del_button"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true" />

<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/scrollView"
android:layout_below="@+id/add_button"
android:layout_marginTop="16dp">

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:id="@+id/display"
android:layout_marginTop="12dp" />
</ScrollView>

</RelativeLayout>

Then. Created java code for control main activity layout
MainActivity.java

//MainActivity.java
package com.example.kornsinmac.kotrealm.activities

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import com.example.kornsinmac.kotrealm.R
import com.example.kornsinmac.kotrealm.entities.Student
import com.example.kornsinmac.kotrealm.model.StudentModel
import io.realm.Realm
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

var studentModel = StudentModel()
var realm = Realm.getDefaultInstance()

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
studentModel = StudentModel()
var stu = Student(
_ID = 160001,
firstName = "kongsin",
lastName = "pansansou",
stuSex = true,
stuClass = 3
)

if (studentModel.getStudents(realm).count() > 0) {
displayStudents(realm)
}

add_button.setOnClickListener {

if (studentModel.getStudents(realm).count() <= 0) {
studentModel.addStudent(realm, stu)
} else {
var v = studentModel.getLastStudent(realm)
var newStudent = v.copy(v._ID + 1)
studentModel.addStudent(realm, newStudent)
}
displayStudents(realm)
}

del_button.setOnClickListener {
studentModel.removeLastStudent(realm)
displayStudents(realm)
}
}

fun displayStudents(realm: Realm) {
var data = ""
var results = studentModel.getStudents(realm)
results.forEach { result ->
data += "$result \n --------------------------------------- \n"
}
display.text = data
}

}

build.gradle in project

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.1.0-beta1'
classpath "io.realm:realm-gradle-plugin:0.88.3"
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}

allprojects {
repositories {
jcenter()
}
}

task clean(type: Delete) {
delete rootProject.buildDir
}

build.gradle in module app

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'realm-android'

android {
compileSdkVersion 23
buildToolsVersion "23.0.2"

defaultConfig {
applicationId "com.example.kornsinmac.kotrealm"
minSdkVersion 17
targetSdkVersion 23
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
sourceSets {
main.java.srcDirs += 'src/main/kotlin'
}
}

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.3.0'
compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
}
buildscript {
ext.kotlin_version = '1.0.1-2'
repositories {
mavenCentral()
}
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath "org.jetbrains.kotlin:kotlin-android-extensions:$kotlin_version"
}
}
repositories {
mavenCentral()
}
One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.