7hsk
7hsk

Reputation: 335

Unresolvered reference: when I call the method of an instance from another activity

I would like to call the method of an instance of AuthActivity from MainActivity. However, I get an error. AuthActivity contains a variable that lets you know if the user has already authenticated from this activity!

Unresolvered reference: checkIfUserAlreadyLogged()

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        FirebaseApp.initializeApp(applicationContext)
        setContentView(R.layout.activity_main)

      
        if (AuthActivity.checkIfUserAlreadyLogged()) {
            return this.displayAuthWithFragment(AuthActivity.HOME_FRAGMENT)
        }

    }
 }

Here is my AuthActivity class:

package com.ksainthi.inance


import androidx.appcompat.app.AppCompatActivity
import androidx.activity.result.contract.ActivityResultContracts
import androidx.fragment.app.Fragment
import com.google.firebase.auth.FirebaseAuth

class AuthActivity : AppCompatActivity() {

    private val firebaseAuth: FirebaseAuth by lazy {
        FirebaseAuth.getInstance()
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_auth)

    }


    fun checkIfUserAlreadyLogged(): Boolean {
        if (this.firebaseAuth.currentUser != null) {
            return true
        }
        return false
    }
 }
 

Upvotes: 0

Views: 51

Answers (1)

Tyler V
Tyler V

Reputation: 10910

If you want to have some code or state variables shared between Activities, they should not live in one of the activities. Activity instances are created and destroyed automatically as a part of the application lifecycle, so getting access to one Activity instance from a different Activity instance is not a feasible/reliable approach.

One way of sharing code between Activities in Kotlin is to make an object class, like this

object FirebaseHelper {

    private val firebaseAuth: FirebaseAuth by lazy {
        FirebaseAuth.getInstance()
    }
    
    fun checkIfUserAlreadyLogged(): Boolean {
        return firebaseAuth.currentUser != null
    }
}

Then you can call FirebaseHelper.checkIfUserAlreadyLogged() from any activity

Upvotes: 1

Related Questions