4

I have a class which I attached an observer to in the constructor:

public class MyStateMgr implements LifecycleObserver {

     public MyStateMgr (LifecycleOwner lifecycleOwner) {
            lifecycleOwner.getLifecycle().addObserver(this);
    }
}

The problem is that I get IllegalArgumentException. I checked about this crash and I saw that "If the observer is already in the list with another owner, LiveData throws an IllegalArgumentException."

I call this constructor only once. How can I check if this observer has another owner? Is there a way to check it? Maybe it's another reason?

This is the crash:

Fatal Exception: java.lang.IllegalArgumentException
       at android.arch.lifecycle.LifecycleRegistry.downEvent(LifecycleRegistry.java:255)
       at android.arch.lifecycle.LifecycleRegistry.backwardPass(LifecycleRegistry.java:306)
       at android.arch.lifecycle.LifecycleRegistry.sync(LifecycleRegistry.java:327)
       at android.arch.lifecycle.LifecycleRegistry.addObserver(LifecycleRegistry.java:188)
       at android.os.Handler.handleCallback(Handler.java:790)
       at android.os.Handler.dispatchMessage(Handler.java:99)
       at android.os.Looper.loop(Looper.java:172)
       at android.os.HandlerThread.run(HandlerThread.java:65)
MorZa
  • 2,215
  • 18
  • 33
  • 1
    you can check it with `hasActiveObservers()` method : https://developer.android.com/reference/android/arch/lifecycle/LiveData.html#hasActiveObservers() – Jeel Vankhede Oct 24 '18 at 05:59
  • Thanks but it only works on a livedata object and I don't have it here, I have observer on "lifecycleOwner.getLifecycle()". – MorZa Oct 24 '18 at 06:14
  • Are you using `LifeCycleObserver` ? In that case, You should check if `LiveData` has active observers in Your LifeCycleOwner. and then if you don't have any then try to observe on it again. Share some code so that i can show you how to. – Jeel Vankhede Oct 24 '18 at 06:19
  • Yes, I'm using LifecycleObserver (I'll edit my post), and what I wrote in the post is the only relevant code... – MorZa Oct 24 '18 at 06:30
  • 1
    What if you remove your observer manually using `lifecycle.removeObserver()`? Check if this solve the exception. call this on destroy method of your lifecycle owner. – Jeel Vankhede Oct 24 '18 at 06:40
  • @JeelVankhede Ok, thanks, I'll try it. – MorZa Oct 24 '18 at 09:18

0 Answers0