My app keeps crashing with FirebaseNetworkException
whenever I don't have an internet connection even though I'm handling the exception, am I missing something?:
fun getToken(): String? {
val token = StringBuilder()
val countDownLatch = CountDownLatch(1)
try {
FirebaseAuth.getInstance().currentUser?.getIdToken(false)
?.addOnCompleteListener { task ->
token.append(task.result?.token)
println(task.result?.token)
countDownLatch.countDown()
}
return try {
countDownLatch.await(30L, TimeUnit.SECONDS)
token.toString()
} catch (ie: InterruptedException) {
null
}
}
catch (exception: FirebaseNetworkException)
{
println("exception is ${exception.message.toString()}")
return null;
}
}
This the error returned:
Caused by: com.google.firebase.FirebaseNetworkException: A network error (such as timeout, interrupted connection or unreachable host) has occurred.
CodePudding user response:
Firebase has provided a method to whether response is success or failure. Reference link.
Returns true if the Task has completed successfully; false otherwise.
if(task.isSuccessful) {}
Also, you can use a callback method to return token, I have make it a more easy for you. In your onCreate()
getToken { token ->
println("Your token $token")
}
Initialize a function with a callback listener
fun getToken(callback: (token: String?) -> Unit) {
FirebaseAuth.getInstance().currentUser?.getIdToken(false)?.addOnCompleteListener { task ->
if (task.isSuccessful) {
callback.invoke(task.result.token)
} else
callback.invoke(null)
}
}