0

I am writing a Kotlin app and using Firestore as my db. I have 2 LiveDatas, to keep my current user's data, defined like so:

private val userDocument = MutableLiveData<DocumentSnapshot?>()
val userData = Transformations.map(userDocument) { it?.toObject(UserModel::class.java) }

somehow userData is null, and all references to it (for example: userData.value?.id) throw:

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object androidx.lifecycle.LiveData.getValue()' on a null object reference

If I add ? (userData?.value?.id) I get the Unnecessary safe call on a non-null receiver of type LiveData<UserModel?> lint. How can Transformations.map(...) return null?

btw: I saw this similar question, but in my case, I do initialize the referedMutableLiveData.

Omer Levy
  • 347
  • 4
  • 11
  • 1
    where do you call `userData`? – IR42 Jul 25 '21 at 15:17
  • Thanks for your fast replay! I just realized I call it in an `init` block before defining `val userData`... – Omer Levy Jul 25 '21 at 15:40
  • I will answer the question to save time for others, because Android Studio doesn't hint that a non-null field might be null if referred before the line defining it. If you prefer, you can write that answer and I'll accept it. – Omer Levy Jul 25 '21 at 15:42

1 Answers1

0

The reason was that I referred to userData before defining it. My code looked like that:

    private val userDocument = MutableLiveData<DocumentSnapshot?>()

    init {
        Authentication.currentUser.observeForever { switchUserDocument(it?.uid ?: "") }
    }

    val userData = Transformations.map(userDocument) { it?.toObject(UserModel::class.java) }

    private fun switchUserDocument(id: String): Task<DocumentSnapshot>? {
        if (id.isEmpty()) {
            ...
        } else if ((userData.value?.id ?: "") != id) {
            ...
        }
    }

I forgot that in Kotlin the order of definition and init blocks matters, and lost some time for that. Hope it will save that time to someone in the future:)

Omer Levy
  • 347
  • 4
  • 11