java.lang.NullPointerException: Attempt to invoke interface method 'void android.text.TextWatcher.beforeTextChanged(java.lang.CharSequence, int, int, int)' on a null object reference
我在我的 Android 应用程序中将 TextWatcher 添加到 TextInputEditText 中,当我开始输入文本或返回到片段时,应用程序抛出此异常并崩溃,我仍然不明白为什么。
这是我的代码,应用程序抛出异常:
class LoginView(
private val binding: FragmentLoginBinding,
private val callback: LoginViewCallback,
) {
init {
initViews()
}
private fun initViews() = with(binding) {
btnLogin.setOnClickListener {
callback.onLoginClick(
UserLoginParams(
etLogin.text.toString(),
etPassword.text.toString().computedMD5Hash()
)
)
}
btnOfferToRegister.setOnClickListener { callback.onOfferToRegisterClick() }
etLogin.addTextChangedListener(loginTextWatcher)
etPassword.addTextChangedListener(loginTextWatcher)
}
fun bind(loginViewState: LoginViewState?) = with(binding) {
loginViewState ?: return
tvError.setTextByReference(loginViewState.loginError?.textReference)
progressBar.setViewVisibility(loginViewState.progressBarVisibility)
btnLogin.setViewVisibility(loginViewState.buttonVisibility)
}
private val loginTextWatcher = object : TextWatcher {
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
callback.onInputFieldsChanged()
}
override fun afterTextChanged(s: Editable?) {
}
}
}
提前谢谢您
我不知道如何解决这个问题,但如果它只是有时发生,你可以这样做
class LoginView(
private val binding: FragmentLoginBinding,
private val callback: LoginViewCallback,
) {
init {
initViews()
}
private fun initViews() = with(binding) {
btnLogin.setOnClickListener {
callback.onLoginClick(
UserLoginParams(
etLogin.text.toString(),
etPassword.text.toString().computedMD5Hash()
)
)
}
btnOfferToRegister.setOnClickListener { callback.onOfferToRegisterClick() }
etLogin.addTextChangedListener(loginTextWatcher)
etPassword.addTextChangedListener(loginTextWatcher)
}
fun bind(loginViewState: LoginViewState?) = with(binding) {
loginViewState ?: return
tvError.setTextByReference(loginViewState.loginError?.textReference)
progressBar.setViewVisibility(loginViewState.progressBarVisibility)
btnLogin.setViewVisibility(loginViewState.buttonVisibility)
}
private val loginTextWatcher = object : TextWatcher {
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
callback.onInputFieldsChanged()
}
override fun afterTextChanged(s: Editable?) {
}
}
}