-
-
Save gartesk/df072f5c3002a23ff723a6b2f8d6c063 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.example.realmqueryplayground | |
import android.os.Bundle | |
import android.support.v7.app.AppCompatActivity | |
import io.realm.Realm | |
import io.realm.RealmConfiguration | |
import junit.framework.Assert.assertTrue | |
import java.util.* | |
class MainActivity : AppCompatActivity() { | |
override fun onCreate(savedInstanceState: Bundle?) { | |
super.onCreate(savedInstanceState) | |
setContentView(R.layout.activity_main) | |
initRealm() | |
compareQueries() | |
} | |
private fun compareQueries() { | |
val results1 = mutableListOf<TestData>() | |
val results2 = mutableListOf<TestData>() | |
doOnRealm { | |
executeTransaction { transactionRealm -> | |
results2.addAll(transactionRealm.where(TestData::class.java) | |
.beginGroup() | |
.equalTo("name", "Bob") | |
.beginGroup() | |
.lessThan("count", 3).or().greaterThan("count", 5) | |
.endGroup() | |
.endGroup() | |
.or().equalTo("active", true) | |
.findAll() | |
.map { TestData(it.name, it.count, it.active) }) | |
} | |
} | |
doOnRealm { | |
executeTransaction { transactionRealm -> | |
results1.addAll(transactionRealm.where(TestData::class.java) | |
.beginGroup() | |
.beginGroup() | |
.lessThan("count", 3).or().greaterThan("count", 5) | |
.endGroup() | |
.equalTo("name", "Bob") | |
.endGroup() | |
.or().equalTo("active", true) | |
.findAll() | |
.map { TestData(it.name, it.count, it.active) }) | |
} | |
} | |
assertTrue(results1.size == results2.size) | |
} | |
private fun initRealm() { | |
Realm.init(this) | |
val realmConfiguration = RealmConfiguration.Builder() | |
.name(Realm.DEFAULT_REALM_NAME) | |
.deleteRealmIfMigrationNeeded() | |
.build() | |
Realm.deleteRealm(realmConfiguration) | |
Realm.setDefaultConfiguration(realmConfiguration) | |
val names = arrayOf("Bruce", "Peter", "Bob", "Greg", "Ivan", "John", "Antony") | |
val random = Random() | |
val testData = (0..99) | |
.map { | |
TestData( | |
names[random.nextInt(names.size)], | |
random.nextInt(7), | |
random.nextBoolean() | |
) | |
} | |
doOnRealm { | |
executeTransaction { transactionRealm -> transactionRealm.copyToRealm(testData) } | |
} | |
} | |
private inline fun doOnRealm(action: Realm.() -> Unit) { | |
var realm: Realm? = null | |
try { | |
realm = Realm.getDefaultInstance() | |
realm.action() | |
} finally { | |
try { | |
realm?.close() | |
} catch (throwable: Throwable) { | |
//ignore | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment