0

I am integrating push notifications in my chat app. so in my registration fragment I am writing this code for the FCM token :

  FirebaseMessaging.getInstance().token.addOnCompleteListener(OnCompleteListener { task ->
                                                            if (!task.isSuccessful) {
                                                                Log.w("TAG", "Fetching FCM registration token failed", task.exception)
                                                                return@OnCompleteListener
                                                            }

                                                            // Get new FCM registration token
                                                            userToken = task.result.toString()
                                                            Log.d("task", userToken)

                                                        })

and after this, I am uploading this token to the firebase database, but I get an error that says

lateinit property userToken has not been initialized  

i don't know why I am getting this error, when I am initializing it right before it will be accessed. if anyone knows where I am wrong, plz help me.

1 Answers1

0

try this

val user = FirebaseAuth.getInstance().currentUser
    var token: String? = null
    val lock = CountDownLatch(1)

user?.getIdToken(true)?.addOnCompleteListener { task ->
    if (task.isSuccessful) {
        userToken = task.result?.token
        if (token == null) {
            lock.countDown()            //<--unlock 
            return@addOnCompleteListener
        }
        //save token
    } else {
        lock.countDown()                //<--unlock 
        return@addOnCompleteListener
    }
}
lock.await() 
Krishan Madushanka
  • 319
  • 1
  • 5
  • 21