I have an interface which is passed to a viewmodel from an activity where its implemented. Then in the viewmodel, it calls the implemented interface method. Inside this method, all I want to do is display a Toast but I am getting null error trying to access the activity context. I do not understand why.
Just to be clear, inside all otber overridden method such as onCreate, onStop, OnResume, etc. If I display the toast, it works fine. Its only when inside this interface method, activity context seems to be null. I have absolutely no idea.
This is the hilt module
@Module
@InstallIn(SingletonComponent::class)
abstract class ToastListenerModule {
@Binds
abstract fun bindToastMessageListener(activity: SplashActivity): ToastMessageListener
}
My SplashActivity.kt
@AndroidEntryPoint
class SplashActivity @Inject constructor() : AppCompatActivity(),ToastMessageListener { private lateinit var binding: ActivitySplashBinding
@Inject
lateinit var auth: FirebaseAuth
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
installSplashScreen()
binding = ActivitySplashBinding.inflate(layoutInflater)
setContentView(binding.root)
}
override fun showToast(message: String) {
//THIS IS WHERE THE PROBLEM IS WITH THE CONTEXT
Toast.makeText(this,"MESSAGE", Toast.LENGTH_SHORT)
}
}
Below I have my ViewModel:
@HiltViewModel
class AuthenticationViewModel @Inject constructor(private val auth:FirebaseAuth, private val toastListner:ToastMessageListener): ViewModel() {
val emailText = ObservableField<String>("")
val passwordText = ObservableField<String>("")
val nameText= ObservableField<String>("")
fun onSubmitClicked(isLogin:Boolean) {
if(isLogin){
val email = emailText.get()
val password = passwordText.get()
if (email.isNullOrEmpty() || password.isNullOrEmpty()) {
println("Email or password is empty")
return
}
auth.signInWithEmailAndPassword(emailText.get()?:"", passwordText.get()?:"")
.addOnCompleteListener() { task ->
if (task.isSuccessful) {
toastListner.showToast("Login Successful")
} else {
val exception = task.exception
//THIS IS WHERE I CALL showToast
//AND YES IT IS GETTING CALLED AND EVERYTHING
toastListner.showToast("Login Failed: ${exception?.message}")
}
}
}else{
println("SIGN Up BUTTON CLICKED ${emailText.get()} ${passwordText.get()}")
}
}
fun isValidInput(): Boolean {
val inputEm = emailText.get() ?: return false
val inputPass = passwordText.get() ?: return false
return inputEm.isNotEmpty() && inputPass.isNotEmpty()
}
}