androidautocompletetextviewaddtextchangedlistener

AutoCompleteTextview with Textwatcher android


I have a small issue with AutoCompleteTextview with textwatcher.

I Have AutoCompleteTextview for Suggestion.The data Comes From API side. With every new word I write in, API is being called and, it gets Response from ApI side and then, The show Dropdown menu for suggestion is shown.So basically that code is in AddTextWatcher Listener.

But when I click on Particular Suggestion, the AddTextwatcher is being Call and it recalls the ApI and the suggestions are shown again!So it is like

-Write in AutoCompleteTextview >> Api is being Called >> Fill in the Data >> Show Suggestions >> and Click On Suggestion >> Show Suggestions again.

Help me with this particular problem. Thanks in Advance.


Solution

    1. Decclare variable :

       private var textWatcher : TextWatcher? = null
       private var selectedItemId: String? = null
      
    2. Initialize the declared variable and apply text watcher as :

      textWatcher = object : TextWatcher { override fun afterTextChanged(char: Editable?) { }

           override fun beforeTextChanged(char: CharSequence?, p1: Int, p2: Int, p3: Int) {}
      
           override fun onTextChanged(char: CharSequence?, p1: Int, p2: Int, p3: Int) {
               if(selectedItemId!=null){
                   return
               }
               callApi()
           }
       }
      
    3. When the response is received from API :

      val adapter = ArrayAdapter(requireActivity(), R.layout.custom_spinner_item, R.id.item_text_view, itemList!!) mBinding.AutoCompleteTextview.setAdapter(adapter )

           mBinding.AutoCompleteTextview.error = null
           mBinding.AutoCompleteTextview.removeTextChangedListener(textWatcher)
           mBinding.AutoCompleteTextview.showDropDown()
      
      
       mBinding.AutoCompleteTextview.setOnItemClickListener { adapterView, view, position, l ->
      
           selectedItemId = adapter.getItem(position)!!.id!!.toString()
           mBinding.AutoCompleteTextview.clearFocus()
      
       }
      
    4. Final step :

      mBinding.AutoCompleteTextview.setOnFocusChangeListener { view, b -> if (b){ mBinding.AutoCompleteTextview.addTextChangedListener(textWatcher) } }