Reputation: 25
I want to search in database using EditText, and then add items to RecylerView. Now i can just search one item, item displays, and after changing edit text it disappears, i want it to stay, i want every item I've searched for to automatically be added to RecyclerView. So I thought I can remove ChangeTextListener, and then add it again to search for another item, and so on(?)
In MainActivity.kt
fun Threads() {
editText.addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(
s: CharSequence, start: Int,
count: Int, after: Int
) {
}
override fun onTextChanged(
s: CharSequence, start: Int,
before: Int, count: Int
) {
Thread {
//here we search for item
val itemsList = db?.costDAO()!!.getByName(s.toString())
runOnUiThread {
//here we pass item to Adapter constructor
recyclerView.adapter = MyAdapter(this@MainActivity, itemsList)
adapter.notifyDataSetChanged()
}
}.start()
}
override fun afterTextChanged(s: Editable) { }
Cost.DAO
@Dao
interface CostDAO {
@Query("select * from cost where name like :name")
fun getByName(name : String) : List<Cost>
Upvotes: 2
Views: 3219
Reputation: 86
The only way to remove the textWatcher from editText, is to have the exact object that you assigned stored somewhere, in a field for example or in a list.
then you can
binding.editText.removeTextChangeWatcher(textWatcher)
or, if you use multiple textWatchers, for example for recyclerView items,
textWatchers.forEach { vh.binding.editText.remoxeTextChangerWatcher(it) }
The only option to remove a textWatcher is to have it's refference stored, otherwise to pass it to the remove method.
Upvotes: 0
Reputation: 71
Robert's answer is incorrect. This will lead to a crash
java.lang.NullPointerException: Attempt to invoke interface method 'void android.text.TextWatcher.beforeTextChanged(java.lang.CharSequence, int, int, int)' on a null object reference
You can't use an anonymous class because you need to store it to remove.
val textWatcher = object :TextWatcher {
override fun afterTextChanged(s: Editable?) {}
override fun beforeTextChanged(
s: CharSequence?,
start: Int,
count: Int,
after: Int
) {}
override fun onTextChanged(
s: CharSequence?,
start: Int,
before: Int,
count: Int
) {
//Do stuff
}
}
binding.etEmail.addTextChangedWatcher(textWatcher)
// do what you need to do and later on
// ...
//
binding.etEmail.removeTextChangeWatcher(textWatcher)
Upvotes: 6
Reputation: 94
To remove a listener you have to set it to null; I know you are using Kotlin but in Java would be something like this:
editText.addTextChangedListener(null);
Hope it helps!
Upvotes: -1