Home > Software engineering >  How to safely deal with a firebase get method trying to access something that doesn't exist
How to safely deal with a firebase get method trying to access something that doesn't exist

Time:01-29

In my current project I have a section where a user essentially enters a key to get the data under that key in firebase. I am using the get method as it only needs to be accessed once. The get method has an on Success and on failure listener and I have the entire thing within a try catch block but for some reason the app still bugs out and does a weird like crash and refresh action when a key that's not in the realtime database is entered. I ran a debug and for some reason when it reaches the get method in this situation instead of going to the catch block it leaves the function completely.

fun joinFinalised(newEmail: String, code: String) {
    if (code.isEmpty()){
        Toast.makeText(this, "No code entered", Toast.LENGTH_SHORT).show()
    } else {
        try {
            fDBRef.child(newEmail.replace(".","~dot~")).get().addOnSuccessListener {
                if (code == it.child("Code").value as String){
                    email = it.child("Email").value as String
                    fDBRef.child(email.replace(".","~dot~")).setValue(newCrew)
                    displayData()
                }
            }.addOnFailureListener{
                Toast.makeText(this, "Join failed", Toast.LENGTH_SHORT).show()
            }
        } catch (e: Exception) {
            Toast.makeText(this, "Join failed", Toast.LENGTH_SHORT).show()
        }
    }
}

The error it gives is java.lang.NullPointerException: null cannot be cast to non-null type kotlin.String which points to the line of the if statement where I compare the code.

CodePudding user response:

I fixed the problem by adding a second try catch around the if statement where the error pointed to

  • Related