1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Android,KotlinでRealm

Last updated at Posted at 2020-08-19
  • Android Studio 4.0.1
  • Kotlin: 1.3.72
  • realm:6.0.2
  • Windows 10

インストール

bundle.gradle(project)

buildscript {
    dependencies {
        classpath "io.realm:realm-gradle-plugin:6.0.2"
    }
}
bundle.gradle(app)
apply plugin: 'kotlin-kapt'
apply plugin: 'realm-android'

初期化

Applicationクラスを作成し、その中でrealmの初期化をする

App.kt
package jp.co.sankosc.sample

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

class App : Application() {
    override fun onCreate() {
        super.onCreate()
        Realm.init(this)
    }
}
AndroidManifest.xml
    <application
        android:name=".App"

Modelを作る

引数なしのコンストラクタがないと、コンパイルが通らないみたいです。

User.kt
package jp.co.sankosc.sample

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

open class User(
    @PrimaryKey var id : String = "",
    @Required var name : String = ""
) : RealmObject()

Activityから使う

MainActivity.kt
package jp.co.sankosc.sample

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import io.realm.Realm
import java.util.*

class MainActivity : AppCompatActivity() {

	override fun onCreate(savedInstanceState: Bundle?) {
		super.onCreate(savedInstanceState)
		setContentView(R.layout.activity_main)

		val id = UUID.randomUUID().toString()
		val user = User(id, "nozaki")
		val realm = Realm.getDefaultInstance()
		realm.executeTransaction {
			it.copyToRealm(user)
		}
		val count = realm.where(User::class.java).equalTo("id", id).count()
		Log.d("sankosc", "count:" + count)
		realm.close()
	}
}
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?