Skip to content

Commit

Permalink
fix: better exceptions handling
Browse files Browse the repository at this point in the history
  • Loading branch information
kirillzyusko committed Jan 12, 2024
1 parent 79eccd7 commit 06ec224
Showing 1 changed file with 18 additions and 10 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package com.reactnativekeyboardcontroller.extensions

import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import android.widget.EditText
import com.facebook.react.views.textinput.ReactEditText
import java.lang.reflect.Field
Expand Down Expand Up @@ -37,18 +38,25 @@ fun EditText.addOnTextChangedListener(action: (String) -> Unit): TextWatcher {
// will be reproducible again.
//
// so here we push our listener to first position to avoid the soft crash
val clazz: Class<*> = ReactEditText::class.java
val field: Field = clazz.getDeclaredField("mListeners")
field.isAccessible = true
val fieldValue = field[this]

try {
val listeners = fieldValue as ArrayList<TextWatcher>

listeners.add(0, listener)
val clazz: Class<*> = ReactEditText::class.java
val field: Field = clazz.getDeclaredField("mListeners")
field.isAccessible = true
val fieldValue = field[this]
val listeners = fieldValue as? ArrayList<*>

if (listeners != null && listeners.all { it is TextWatcher }) {
// fieldValue is an ArrayList<TextWatch>
val textWatchListeners = listeners as ArrayList<TextWatcher>

textWatchListeners.add(0, listener)
} else {
Log.w(javaClass.simpleName, "Can not attach listener because `fieldValue` does not belong to `ArrayList<TextWatcher>`")
}
} catch (e: ClassCastException) {
// Handle the case where the cast failed
// in this case we don't attach a listener ¯\_(ツ)_/¯
Log.w(javaClass.simpleName, "Can not attach listener because casting failed: ${e.message}")
} catch (e: NoSuchFieldException) {
Log.w(javaClass.simpleName, "Can not attach listener because field `mListeners` not found: ${e.message}")
}

return listener
Expand Down

0 comments on commit 06ec224

Please sign in to comment.