Git Product home page Git Product logo

kotlin-realm-extensions's Introduction

Simplify your code to its minimum expression with this set of Kotlin extensions for Realm. Forget all boilerplate related with Realm API and perform database operations in one line of code with this lightweight library. Full test coverage.

Download for Kotlin 1.3 and Realm 5.9

Grab via Gradle:

repositories {
    mavenCentral()
}

implementation "com.github.vicpinm:krealmextensions:2.5.0"

//For Single and Flowable queries:
implementation 'io.reactivex.rxjava2:rxjava:2.1.16'
implementation 'io.reactivex.rxjava2:rxandroid:2.0.2'

Previous versions of Kotlin and Realm

  • Version 2.4.0 for Kotlin 1.3.x and Realm 5.8.x
  • Version 2.3.0 for Kotlin 1.3.x and Realm 5.7.x
  • Version 2.2.0 for Kotlin 1.2.x and Realm 5.0.x
  • Version 2.1.3 for Kotlin 1.2.x and Realm 4.3.x
  • Version 2.0.0 for Kotlin 1.1.x and Realm 4.1.x
  • Version 1.2.0 for Kotlin 1.1.x and Realm 3.5.x
  • Version 1.0.9 for Kotlin 1.1.x and Realm 3.1.x
  • Version 1.0.6 for Kotlin 1.1.x and Realm 2.2.x

Features

Forget about:

  • Realm instances management
  • Transactions
  • Threads limitations
  • Boilerplate related with Realm API
  • From 2.0 version, your database entities can either extend from RealmObject or implement RealmModule interface.

Usage

All methods below use Realm default configuration. You can use different Realm configurations per model with RealmConfigStore.init(Entity::class.java, myConfiguration). See application class from sample for details. Thanks to @magillus for its PR.

Store entities

All your entities should extend RealmObject.

Before (java)

User user = new User("John");

Realm realm = Realm.getDefaultInstance();
try{
   realm.executeTransaction(realm -> {
      realm.copyToRealmOrUpdate(user);  
   });  
} finally {
   realm.close();
}

After (Kotlin + extensions)

User("John").save()

Save method creates or updates your entity into database. You can also use create() method, which only create a new entity into database. If a previous one exists with the same primary key, it will throw an exception.

Save list: Before (java)

List<User> users = new ArrayList<User>(...);

Realm realm = Realm.getDefaultInstance();
try {
    realm.executeTransaction(realm -> {
        realm.copyToRealmOrUpdate(users);  
    });
} finally {
    realm.close();
}

Save list: After (Kotlin + extensions)

listOf<User>(...).saveAll()

If you need to provide your own Realm instance, you can use the saveManaged(Realm) and saveAllManaged(Realm) methods. These methods return managed objects. You should close manually your Realm instance when you finish with them.

Query entities

  • All query extensions return detached realm objects, using copyFromRealm() method.
  • All query extensions has two versions. One is an extension of RealmModel, and you need to create an instance of that model to perform your query. The other version is a global parametrized funcion (thanks to @PrashamTrivedi). See below examples for details.

Get first entity: Before (java)

Realm realm = Realm.getDefaultInstance();
try {
   Event firstEvent = realm.where(Event.class).findFirst();
   firstEvent = realm.copyFromRealm(event);
} finally {
   realm.close();
}

Get first entity: After (Kotlin + extensions)

val firstEvent = Event().queryFirst() //Or val first = queryFirst<Event> 

You can use lastItem extension too.

Get all entities: Before (java)

Realm realm = Realm.getDefaultInstance();
try {
    List<Event> events = realm.where(Event.class).findAll();
    events = realm.copyFromRealm(event);
} finally {
    realm.close();
}

Get all entities: After (Kotlin + extensions)

val events = Event().queryAll() //Or queryAll<Event>

Get entities with conditions: Before (java)

Realm realm = Realm.getDefaultInstance();
try{
    List<Event> events = realm.where(Event.class).equalTo("id",1).findAll();
    events = realm.copyFromRealm(event);
} finally {
    realm.close();
}

Get entities with conditions: After (Kotlin + extensions)

val events = Event().query { equalTo("id",1) } //Or query<Event> { ... }
//NOTE: If you have a compilation problems in equalTo method (overload ambiguity error), you can use equalToValue("id",1) instead

If you only need the first or last result, you can also use:

val first = Event().queryFirst { equalTo("id",1) }
val last = Event().queryLast { equalTo("id",1) }

Get sorted entities

val sortedEvents = Event().querySorted("name",Sort.DESCENDING) 
val sortedEvents = Event().querySorted("name",Sort.DESCENDING) { equalTo("id",1) }

Delete entities

Delete all: Before (java)

Realm realm = Realm.getDefaultInstance();
try{
    List<Event> events = realm.where(Event.class).findAll();
    realm.executeTransaction(realm -> {
        events.deleteAllFromRealm();
    });
} finally {
    realm.close();
}

Delete all: After (Kotlin + extensions)

Event().deleteAll() //Or deleteAll<Event>

Delete with condition: Before (java)

Realm realm = Realm.getDefaultInstance();
try{
    List<Event> events = realm.where(Event.class).equalTo("id",1).findAll().deleteAllFromRealm();
    events = realm.copyFromRealm(event);
} finally {
    realm.close();
}

Delete with condition: After (Kotlin + extensions)

Event().delete { equalTo("id", 1) }

Observe data changes

Before (java)

Realm realm = Realm.getDefaultInstance();
Flowable<List<Event>> obs =  realm.where(Event.class).findAllAsync()
.asFlowable()
.filter(RealmResults::isLoaded)
.map(realm::copyFromRealm)
.doOnUnsubscribe(() -> realm.close());

After (Kotlin + extensions)

val obs = Event().queryAllAsFlowable() //Or queryAllAsFlowable<Event>

Observe query with condition: Before (java)

Realm realm = Realm.getDefaultInstance();
Flowable<List<Event>> obs =  realm.where(Event.class).equalTo("id",1).findAllAsync()
.asFlowable()
.filter(RealmResults::isLoaded)
.map(realm::copyFromRealm)
.doOnUnsubscribe(() -> realm.close());

Observe query with condition: After (Kotlin + extensions)

val obs = Event().queryAsFlowable { equalTo("id",1) }

These kind of observable queries have to be performed on a thread with a looper attached to it. If you perform an observable query on the main thread, it will run on this thread. If you perform the query on a background thread, a new thread with a looper attached will be created for you to perform the query. This thread will be listen for data changes and it will terminate when you call unsubscribe() on your subscription.

RxJava 2 Single support (thanks to @SergiyKorotun)

val single = Event().queryAllAsSingle()
val single = Event().queryAsSingle { equalTo("id", 1) }

Transactions

If you need to perform several operations in one transaction, you can do:

executeTransaction {
   User().deleteAll() //Or deleteAll<User>()
   newUsers.saveAll()
}

Threads management

Realm needs to perform observable queries and async queries in a thread with a looper attached to it. This library has that into account, and when you perform queries like queryAsFlowable, queryAsSingle, queryAsync and all other variants, a new thread with a looper attached to it will be created for you if the thread from where you execute the query does not have a looper attached. This thread created by the library will be finished automatically when the subscription is finished, or when the async query return its result.

Proguard

You need to add these rules if you use proguard, for rxjava and realm:

-keep class com.vicpin.krealmextensions.** 
-keepnames public class * extends io.realm.RealmObject
-keepnames public class * extends io.realm.RealmModel
-keep class io.realm.annotations.RealmModule
-keep @io.realm.annotations.RealmModule class *
-keep class io.realm.internal.Keep
-keep @io.realm.internal.Keep class *
-dontwarn io.realm.**

kotlin-realm-extensions's People

Contributors

akshaychordiya avatar jhkatestsoft avatar qiantao94 avatar ravidsrk avatar s0nerik avatar sergiykorotun avatar vicpinm avatar victordigio avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

kotlin-realm-extensions's Issues

Proguard rules

H Antonio, this library is awesome!
Although I've noticed that the proguard rules are missing in the Readme.md, could you add them? I'm having problems building when minify is enabled.

Cannot use classes which implement RealmModel

Compilation fails with the following message:

e: /media/hdd/dev/quest/app/build/generated/source/kapt/debug/io/realm/KotlinTournamentRealmProxy.java:10: error: cannot find symbol
e:

e: import io.realm.internal.LinkView;
e: ^
e: symbol: class LinkView
e: location: package io.realm.internal
e: java.lang.IllegalStateException: failed to analyze: org.jetbrains.kotlin.kapt3.diagnostic.KaptError: Error while annotation processing
at org.jetbrains.kotlin.analyzer.AnalysisResult.throwIfError(AnalysisResult.kt:57)
at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler.compileModules(KotlinToJVMBytecodeCompiler.kt:137)
at org.jetbrains.kotlin.cli.jvm.K2JVMCompiler.doExecute(K2JVMCompiler.kt:158)
at org.jetbrains.kotlin.cli.jvm.K2JVMCompiler.doExecute(K2JVMCompiler.kt:61)
at org.jetbrains.kotlin.cli.common.CLICompiler.execImpl(CLICompiler.java:107)
at org.jetbrains.kotlin.cli.common.CLICompiler.execImpl(CLICompiler.java:51)
at org.jetbrains.kotlin.cli.common.CLITool.exec(CLITool.kt:92)
at org.jetbrains.kotlin.daemon.CompileServiceImpl$compile$1$2.invoke(CompileServiceImpl.kt:386)
at org.jetbrains.kotlin.daemon.CompileServiceImpl$compile$1$2.invoke(CompileServiceImpl.kt:96)
at org.jetbrains.kotlin.daemon.CompileServiceImpl$doCompile$$inlined$ifAlive$lambda$2.invoke(CompileServiceImpl.kt:892)
at org.jetbrains.kotlin.daemon.CompileServiceImpl$doCompile$$inlined$ifAlive$lambda$2.invoke(CompileServiceImpl.kt:96)
at org.jetbrains.kotlin.daemon.common.DummyProfiler.withMeasure(PerfUtils.kt:137)
at org.jetbrains.kotlin.daemon.CompileServiceImpl.checkedCompile(CompileServiceImpl.kt:919)
at org.jetbrains.kotlin.daemon.CompileServiceImpl.doCompile(CompileServiceImpl.kt:891)
at org.jetbrains.kotlin.daemon.CompileServiceImpl.compile(CompileServiceImpl.kt:385)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:346)
at sun.rmi.transport.Transport$1.run(Transport.java:200)
at sun.rmi.transport.Transport$1.run(Transport.java:197)
at java.security.AccessController.doPrivileged(Native Method)
at sun.rmi.transport.Transport.serviceCall(Transport.java:196)
at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:568)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:826)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$0(TCPTransport.java:683)
at java.security.AccessController.doPrivileged(Native Method)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:682)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: org.jetbrains.kotlin.kapt3.diagnostic.KaptError: Error while annotation processing
at org.jetbrains.kotlin.kapt3.AnnotationProcessingKt.doAnnotationProcessing(annotationProcessing.kt:90)
at org.jetbrains.kotlin.kapt3.AnnotationProcessingKt.doAnnotationProcessing$default(annotationProcessing.kt:42)
at org.jetbrains.kotlin.kapt3.AbstractKapt3Extension.runAnnotationProcessing(Kapt3Extension.kt:205)
at org.jetbrains.kotlin.kapt3.AbstractKapt3Extension.analysisCompleted(Kapt3Extension.kt:166)
at org.jetbrains.kotlin.kapt3.ClasspathBasedKapt3Extension.analysisCompleted(Kapt3Extension.kt:82)
at org.jetbrains.kotlin.cli.jvm.compiler.TopDownAnalyzerFacadeForJVM$analyzeFilesWithJavaIntegration$2.invoke(TopDownAnalyzerFacadeForJVM.kt:96)
at org.jetbrains.kotlin.cli.jvm.compiler.TopDownAnalyzerFacadeForJVM.analyzeFilesWithJavaIntegration(TopDownAnalyzerFacadeForJVM.kt:106)
at org.jetbrains.kotlin.cli.jvm.compiler.TopDownAnalyzerFacadeForJVM.analyzeFilesWithJavaIntegration$default(TopDownAnalyzerFacadeForJVM.kt:83)
at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler$analyze$1.invoke(KotlinToJVMBytecodeCompiler.kt:376)
at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler$analyze$1.invoke(KotlinToJVMBytecodeCompiler.kt:67)
at org.jetbrains.kotlin.cli.common.messages.AnalyzerWithCompilerReport.analyzeAndReport(AnalyzerWithCompilerReport.kt:96)
at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler.analyze(KotlinToJVMBytecodeCompiler.kt:367)
at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler.compileModules(KotlinToJVMBytecodeCompiler.kt:132)
... 30 more

Support for RealmModel

What do you think about adding support for RealmModel interface?

I'm not 100% sure if this would be important to other users, because even if you only implement RealmModel and add RealmClass annotation you still cannot extend from different classes then RealmObject. But still there may be some users that prefer this approach.

If you think this would be a nice to have feature I can prepare a PR to discuss :)

deleteAllManaged()

This library is really handy.

Is there a way to delete all from a managed instance? kind of like when you call .saveAllManaged()
so I can delete only from the managed instance?

Detached Realm objects

Why queries return only detached objects? Isn't Realm so great because of data attached to it's reference?

Great work btw. 👍

Duplicate files copied in APK

Adding
compile "com.github.vicpinm:krealmextensions:1.1.5"
to build.gradle and then I get below error:

Error:Execution failed for task ':app:transformNativeLibsWithMergeJniLibsForAcceptanceDebug'.
> com.android.build.api.transform.TransformException: com.android.builder.packaging.DuplicateFileException: Duplicate files copied in APK lib/x86/librealm-jni.so
  	File1: /Users/jimclermonts/.android/build-cache/bc13ffa1b029cd028a6eb021e00d5ca54a338816/output/jni
  	File2: /Users/jimclermonts/.android/build-cache/628132c7935bf52aecbded43d68d9a18b028d8ba/output/jni

Query is inaccessible to RealmExtensionsKt

Hi! Thank you for the lib!
I'm having the following problem when I try to access my Realm Object:
java.lang.IllegalAccessError: Method 'io.realm.RealmQuery io.realm.RealmQuery.createQuery(io.realm.Realm, java.lang.Class)' is inaccessible to class 'com.vicpin.krealmextensions.RealmExtensionsKt' (declaration of 'com.vicpin.krealmextensions.RealmExtensionsKt' appears in /data/app/ch.farmy.myApp-8cgk5W4ugikhcBaGovMlRw==/base.apk)

Live data extension

Nice tools,

Is there a way to achieve the same observables extensions with live data ?

ObservableList in result

Hello,

I would to query my object and have in result an ObservableList. I need this to use the lib with the lib LastAdapter, is it possible ?

Thank's

Does not work with Realm 5.8.0

Upon lowering the version to Realm 5.7.0 the code works fine but when I update the version to 5.8.0, and try to save a realm object, it gives me the following exception

 Caused by: java.lang.NoSuchMethodError: No virtual method copyToRealm(Lio/realm/RealmModel;)Lio/realm/RealmModel; in class Lio/realm/Realm; or its super classes (declaration of 'io.realm.Realm' appears in /data/app/com.allective-KIOgR_c-RriD_qNKZ3EWpQ==/split_lib_dependencies_apk.apk)
        at com.vicpin.krealmextensions.RealmExtensionsKt$save$1.invoke(RealmExtensions.kt:266)
        at com.vicpin.krealmextensions.RealmExtensionsKt$save$1.invoke(Unknown Source:2)
        at com.vicpin.krealmextensions.RealmExtensionsKt$transaction$$inlined$use$lambda$1.execute(RealmExtensions.kt:198)
        at io.realm.Realm.executeTransaction(Realm.java:1493)
        at com.vicpin.krealmextensions.RealmExtensionsKt.transaction(RealmExtensions.kt:198)
        at com.vicpin.krealmextensions.RealmExtensionsKt.save(RealmExtensions.kt:262)
        at com.allective.api.ApiImplementation$getLogin$1.accept(ApiImplementation.kt:39)
        at com.allective.api.ApiImplementation$getLogin$1.accept(ApiImplementation.kt:18)
        at io.reactivex.internal.observers.LambdaObserver.onNext(LambdaObserver.java:63)
        at io.reactivex.internal.operators.observable.ObservableObserveOn$ObserveOnObserver.drainNormal(ObservableObserveOn.java:201)
        at io.reactivex.internal.operators.observable.ObservableObserveOn$ObserveOnObserver.run(ObservableObserveOn.java:255)
        at io.reactivex.android.schedulers.HandlerScheduler$ScheduledRunnable.run(HandlerScheduler.java:119)
        at android.os.Handler.handleCallback(Handler.java:789) 
        at android.os.Handler.dispatchMessage(Handler.java:98) 
        at android.os.Looper.loop(Looper.java:164) 
        at android.app.ActivityThread.main(ActivityThread.java:6798) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767) 

Issue with generic type.

I defined an base interface for my repo like this.

interface BaseDataStore<T : RealmObject> {

    fun getObject(): T
    fun getPrimaryKeyAttribute(): String
    fun getPrimaryKey(item: T): String

    fun add(item: T): Completable {
        return Completable
                .fromAction { item.save() }
}

It was compiling with 1.x version, but I just updated with latest version of realm extension + realm 3.5 => real 4.1 an this is not compiling anymore:

I get: cannot use t as reified type parameter use class instead

Please remove application params. from Manifest file

I get several manifest file merge errors when trying to import the lib
Would it be possible to remove

android:allowBackup="true" 
android:label="@string/app_name"
android:supportsRtl="true"

Are these actually needed, hence it's a library.

Perform Migration

Hi, I need a little help with realm migration For Kotlin. I know in Java after creating a migration class that extends from io.realm.ReamMigration, you can use the class asrealmConfiguration = RealmConfiguration.Builder() .schemaVersion(REALM_SCHEMA_VERSION) .migration(**new RealmMigration()**) .build()
How can I do same in Kotlin, new RealmMigration() isn't working for me

Mutliple equalTo

Hello,
I would like avoid the filter{} like my sample
val documentsNotGetCount = RDocument().query { equalToValue("mission.id", mission?.id!! ) }.filter { rDocument -> !rDocument.is_get }.count()

Is it possible ?

Than,k's

save() method getting stuck

I`ve updated kotlin from 1.3.11 to 1.3.20 and after that save() method not working. Just stuck on it. Tested with all combinations of realm\extensions versions. Please check and update libs to work with 5.9 realm and 1.3.20 kotlin. Thanks

Performance overhead

I tried to use this library for my project. When I queried realm db via this library it returns "copyFromRealm" value. This will hardly affects the query performance.

Is there any way to get live Realm object with Realm instances management facility?

Thanks for this library. Let's rock realm world.

save() overrides primary instead of updating object

Hi,
so this is my class:

@AutoIncrementPK
open class Contact() : RealmObject() {
    @PrimaryKey
    var id: Long? = null
    var name: String = ""
    var publicKey: String = ""

    constructor(name: String, publicKey: String) : this() {
        this.name = name
        this.publicKey = publicKey
    }
}

I tried to do an update on an object like this:

contact.name = name
contact.save()

And instead of updating the object, a new object with these properties and new id is created. I checked the code and obviously the line initPk in save overrides the primary. I don't think that this is intended to happen, is it?

Find this AND this query

I am using your extension, but I noticed that I want to do a AND query like this:
RealmResults<Person> r1 = realm.where(Person.class) .equalTo("dogs.name", "Fluffy") .equalTo("dogs.color", "Brown") .findAll();

do you have a method to do this? or with the methods that are in your README, Can I do this?
I'll be grateful with your answer, thank you

Accessing Kotlin Extension from Java

Do I have to always pass an object from Java to access the kotlin extenion like below?

final ChatConversationsRealm F = new ChatConversationsRealm();
List<ChatConversationsRealm> xx = RealmExtensionsKt.queryAll(F);

Is there any way to access it without creating an object but just by specifying the type like RealmExtensionsKt.queryAll(ChatConversationsRealm.class)?

copyFromRealm as an option in FlowableExtensions

On every request (most notably for Flowable) the results are mapped using copyFromRealm

   result.asFlowable()
            .filter { it.isLoaded }
            .map { **realm.copyFromRealm(it)** }
            .subscribe({
                subscriber.onNext(it)
            }, { subscriber.onError(it) })

This is certainly not desirable in every case and would be ideal to have the option to have a locally copied version of the objects or the managed realm backed version.

Consider the following example :

class Parent : RealmObject() {
var id:String?=null
var children:RealmList?=RealmList<>()
}

class Child:RealmObject() {
var id:String?=null
}

If I use a function like queryAllAsFlowable() on the Parent.class and want to display the attribute "children" backed by changes in the DB as a Flowable<RealmList> then this is not possible easily as it could be if the objects emitted were back by realm. If the objects emitted by the functions in RealmExtensionsFlowable were backed by Realm then I could simply do parent.children.asFlowable().

I could of course change the data model to make this work with the current lib, but it would be a shame.

Thank you for the lib in advance and hope I was clear?

Enhancement: Allow parameterized query calls.

Currently to query, I have to write something like this
val events = Event().query { query -> query.equalTo("id",1) }

Which according to me

  • Not memory efficient: Because I need to initialize one empty object just to query.
  • Not idiomatic: There is a better way to write this query functions.

I think the better way of writing query functions should be something like this

val events = query<Event> {query -> query.equalTo("id", 1) }

This feels more idiomatic and looks memory friendly.

Param Query<T> ignored

I'm using Realm Extensions but currently no all our code is on Kotlin we have several layers that will need to refactor (Java), I know extensions are not supported on java, that why I created like and Grapper on kotlin that recieve RealmQuery instead of Query

I'd like to know (if you know). How I can made the compatibility between Query injected from a java class as RealmQuery.

I'm already know that you defined as

public typealias Query<T>  = io.realm.RealmQuery<T>.() -> kotlin.Unit

Where I supposed if you inject a field as RealmQuery should be supported, but seems like you library ignore my RealmQuery injected cuz isn't a Query

There's my example wrapper created in Kotlin it receive a class, fieldName, order and _query

    override fun <T : RealmObject> querySortedObjects(_clazz: Class<T>, _fieldName: String, _order: Sort, _query: RealmQuery<T>): List<T> {
        val newInstance = _clazz.newInstance()
        val results = newInstance.querySorted(_fieldName, _order, {
            _query
        })

        Timber.d("$javaClass -> querySortedObjects: ${_clazz.javaClass} results: ${results.size}")

        return results
    }

   override  fun <T : RealmObject> queryByClass(_clazz: Class<T>): RealmQuery<T>? {
        return try {
            Realm.getDefaultInstance().where(_clazz)
        }catch (e : Exception){
            null
        }
    }


And there's my code provide from java.

    @Override
    public List<User> getFavorites(@NotNull String query) {

        RealmQuery<User> userRealmQuery = mRealmProvider.queryByClass(User.class);

        if (userRealmQuery != null){

            userRealmQuery.equalTo("favorite", true);

            if (query.length() > 0)
                userRealmQuery.and().contains("name", query, Case.INSENSITIVE);

            userRealmQuery.isNotNull("name");

            return mRealmProvider.querySortedObjects(User.class, "name", Sort.ASCENDING, userRealmQuery);
        }
        return new ArrayList<>();
    }

Seems ignore my RealmQuery param

screen shot 2018-02-15 at 1 46 59 pm

Then seems just perform this


val results = newInstance.querySorted(_fieldName, _order)

@linkingObject return always null

i want to get the parent of specific object i have implemented this code

open class Parent() : RealmObject(){
  var steps: RealmList<Child>? =RealmList()}

and in Child

@LinkingObjects("steps")
    val parent: RealmResults<Parent>? = null

when i do this query StepDataStore.getObject().query { equalTo("parent.id", id, Case.INSENSITIVE) } }
i get always null

More than one file was found with OS independent path 'lib/x86/librealm-jni.so'

Hello,
I can't make your extension work, I've got this error when I build :

Execution failed for task ':app:transformNativeLibsWithMergeJniLibsForDebug'.

More than one file was found with OS independent path 'lib/x86/librealm-jni.so'

I tried to clean, rebuild but it still doesn't work.
It looks like a conflict but I really have no idea of how to solve it.
I tried with an all new empty project too (I just included all the libraries I use in my main project)

Edit : I just saw this issue an it does solve the problem but according to realm documentation :

Enabling Realm Mobile Platform: Before your application can synchronize with the Realm Object Server, it has to be enabled in your build file. Add this to the application’s build.gradle:
realm {
syncEnabled = true;
}

So this line is necessary to make object server work. So, can your extensions work with it?

This is my project gradle file :

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

buildscript {
ext.kotlin_version = '1.1.51'
repositories {
    google()
    jcenter()
}
dependencies {
    classpath 'com.android.tools.build:gradle:3.0.0'
    classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    classpath 'io.realm:realm-gradle-plugin:4.1.1'
    classpath 'com.google.gms:google-services:3.0.0'
    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
}
}

allprojects {
repositories {
    google()
    jcenter()
    maven { url "https://jitpack.io" }
}
}

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

And my app gradle file :

apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

apply plugin: 'kotlin-kapt'

apply plugin: 'realm-android'

android {
compileSdkVersion 26
defaultConfig {
    applicationId "com.ledet.benjamin.budgetmanager"
    minSdkVersion 21
    targetSdkVersion 26
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
    def host = "118.121.198.145"
    debug {
        buildConfigField "String", "OBJECT_SERVER_IP", "\"${host}\""
    }
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        buildConfigField "String", "OBJECT_SERVER_IP", "\"${host}\""
    }
}
dataBinding {
    enabled = true
}
}

realm {
    syncEnabled = true
}

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation"org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'

// Dependency for Google Sign-In
compile 'com.google.android.gms:play-services-auth:11.6.0'

// Dependency for Facebook Sign-in
compile 'com.facebook.android:facebook-android-sdk:4.22.1'

// Google support library
compile 'com.android.support:cardview-v7:26.1.0'
compile 'com.android.support:support-v4:26.1.0'
compile 'com.android.support:customtabs:26.1.0'
kapt "com.android.databinding:compiler:3.1.0-alpha02"

//Anko
compile 'org.jetbrains.anko:anko-commons:0.10.1'
compile "org.jetbrains.anko:anko-design:0.10.1"

//Realm
compile "com.github.vicpinm:krealmextensions:2.0.0-beta1"

//For Single and Flowable queries:
compile 'io.reactivex.rxjava2:rxjava:2.1.5'
compile 'io.reactivex.rxjava2:rxandroid:2.0.1'

// Other libraries
compile 'com.squareup.picasso:picasso:2.5.2'
compile 'com.github.lzyzsd:circleprogress:1.2.1'
compile 'com.amulyakhare:com.amulyakhare.textdrawable:1.0.1'
}

apply plugin: 'com.google.gms.google-services'

io.realm.RealmQuery.createQuery(io.realm.Realm, java.lang.Class)' is inaccessible to class 'com.vicpin.krealmextensions.RealmExtensionsKt' .

I have the following crash which slashdot and google do not have any information on...

Process: com.agersens.eshepardcollarfitter.production, PID: 9241
java.lang.IllegalAccessError: Method 'io.realm.RealmQuery io.realm.RealmQuery.createQuery(io.realm.Realm, java.lang.Class)' is inaccessible to class 'com.vicpin.krealmextensions.RealmExtensionsKt' (declaration of 'com.vicpin.krealmextensions.RealmExtensionsKt' appears in /data/app/com.agersens.eshepardcollarfitter.production-1/split_lib_dependencies_apk.apk)
at com.vicpin.krealmextensions.RealmExtensionsKt.forEntity(RealmExtensions.kt:246)
at com.vicpin.krealmextensions.RealmExtensionsKt.queryFirst(RealmExtensions.kt:41)
at com.maiatehcology.maialibrary.syncframework.database.DatabaseWrapper.fetchAnimals(DatabaseWrapper.kt:78)

Any hints as to why this might be happening... I used Kotlin realm extensions in another app and it worked and I can't figure out what I did different other than creating two modules, one for the app and one for all the network and realm code...

Can't seem to use Migrations

Maybe I'm crazy but I can't figure out how to use your library and migrate the schema when I add a new Realm class. All of your code appears to pull the default instance?
The only thing I can see is the sample:

        RealmConfigStore.init(User::class.java, userAddressConfig)
        RealmConfigStore.init(Address::class.java, userAddressConfig)

Does that mean if I use migrations I need to init for every class? But you only use a single config (userAddressConfig) which makes it confusing.

RealmConfiguration update

I think right now the extensions are limited to single RealmConfiguration (default).

Maybe we can introduce a extension method that would wrap into additional configurations, like:
User("testuser").realm(realmConfig).save() or User("testuser").save(realmConfig)

Or even remember configuration per Module/RealmObject or set it via initialization.

Query error: "Overload resolution ambiguity"

When trying to make a query that is not for a string, marks

Error:(128, 36) Overload resolution ambiguity:
public open fun equalTo(p0: String!, @Nullable p1: Byte?): RealmQuery<Notification!>! defined in io.realm.RealmQuery
public open fun equalTo(p0: String!, @Nullable p1: Int?): RealmQuery<Notification!>! defined in io.realm.RealmQuery
public open fun equalTo(p0: String!, @Nullable p1: Long?): RealmQuery<Notification!>! defined in io.realm.RealmQuery
public open fun equalTo(p0: String!, @Nullable p1: Short?): RealmQuery<Notification!>! defined in io.realm.RealmQuery

This is the query

Notification().queryAsObservable{
    query -> query.equalTo("status", 0)
}.subscribe { result ->
    //Do something
}

How to use QueryAllAsync?

Hi, I'm Using realm object server, but I want to know how it is used with sync, because in the README isn't anything about how to use it, Hope your answer, and thank you for your help.

Query throws exeption

Am I missing something? thanks :)

CartModel().queryFirst { it.equalsTo("_ID", 1) }
Method threw 'java.lang.ClassNotFoundException' exception.

this is my class
open class CartModel(
@PrimaryKey open var _ID: Int = 0,
open var qty: Int = 0,
open var foodTitle: String = "",
open var foodDes: String = "",
open var price: String = "",
open var previewURL: String = ""
) : RealmObject() {
fun copy(
_ID: Int = this._ID,
qty: Int = this.qty,
foodTitle: String = this.foodTitle,
foodDes: String = this.foodDes,
price: String = this.price,
previewURL: String = this.previewURL
) = CartModel(_ID, qty, foodTitle, foodDes, price, previewURL)
}

RxJava2 support

Hey there, is there any plan to migrate to RxJava2 for your library? Currently, I'm getting conflicts during compilation when using RxJava2 and Kotlin-Realm-Extensions.

Thank you

Realm Extensions unit test

This library is amazing!, I just have a concern, actually I replaced my old realm storage layer by Realm Extensions, that it's great, but I just discovered you don't have any realm extensions unit testing.

I just would like if you have any example or something like that cuz seems Mockito is not supporting yours extensions :/

Remove RxJava 1 and 2 dependency.

I think pushing for RxJava in the library is too much, making it not dependent on it and adding on extension for RxJava 1 and separate extension RxJava2 would be better
I already had issue where I needed to add because of dual versioning of RxJava usage
packagingOptions { // because- com.github.vicpinm:krealmextensions exclude 'META-INF/rxjava.properties' }

Model migrations DSL (using inline functions)

Hi,
your library seems very interesting, I have been thinking about making the migration definitions more readable. Right now, I see as the best option to provide inline functions so you can write them like Anko does for layouts. What do you think? Once we agree on a way to add it, I will send a PR

Example:

val migration = realmMigration {
    migrate(fromVersion = 1) {
        newModel<MyModel>() {
            field<String>(name = "id") {
                primaryKey = true
            }
            field<Int>(name = "number")
        }
    }
    
    ...
}

Excessive looper threads with RealmExtensionFlowable

I am building a fairly large application using this library. We've noticed on older devices that performance is poor. We identified the problem to be that the RealmExtensionsFlowable file creates a new thread and looper for every subscription if it's not already on the main thread. This causes a large number of threads with loopers, all contending for limited resources. To better understand scope -- we're using Nexus 5 and Nexus 6P as poor performing devices with 10s-20s lockups. Pixel 2 you don't really notice anything.

As a short-term solution, I forked the repo and replaced the thread creation with a singleton thread with a looper. All the performance issues go away. You can see the commit here bricestacey@e07ebab

I'm curious what we might be able to do to allow this behavior to be configurable. Off the top of my head

  1. Add a parameter to the flowable extensions to specify a scheduler
  2. Refactored to use some default LooperFactory, then expose a means of configuring it

I kind of think both are desirable. 1 is sufficient, but 2 would allow setting a default case or more complex strategies. I have only been using Kotlin a few months and this is the only extension library I'm using outside the core android one. I haven't seen anything yet for how to configure them so don't have much insight.

Happy to take a stab at this, but wanted to bring it up before I started down some haphazard path.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.