Get KotlinNullPointerException when open initial fragment

Viewed 95

Get KotlinNullPointerException when open initial fragment when init my uid:

fun setInitialData() {
        firebaseUser = FirebaseAuth.getInstance().currentUser
        databaseReference = FirebaseDatabase.getInstance().reference
        uid = firebaseUser!!.uid

But if I replace initialization on firebaseUser?.uid database data will not load immediately. So understand this the right approach? Also i understand how extra the decision to do some pause before data is loaded?

2 Answers

According to the official documentation regarding FirebaseUser's getCurrentUser() method:

Returns the currently signed-in FirebaseUser or null if there is none.

And to answer your question:

So understand this the right approach?

No, you need to always use getCurrentUser() != null to check if a user is signed in or not.

Also i understand how extra the decision to do some pause before data is loaded?

There is no need to pause something in this case.

Firebase auth can't be initialized when an activity or a fragment is created as it takes time to become responsive. Try to pass it in a button click or anywhere other than oncreate.

Related