androidsearchgridvieweditbox

Textwatcher doesn't recognize space


I am trying to filter a gridview and for that I am entering the data in an editbox. It works great except that when I insert a space character in editbox it somehow doesn't recognize it and the result set comes empty. Please help

Here is my editbox listener:

search.addTextChangedListener(new TextWatcher(){

    @Override
    public void afterTextChanged(Editable arg0) {}

    @Override
    public void beforeTextChanged(CharSequence arg0, int arg1,
            int arg2, int arg3) {}

    @Override
    public void onTextChanged(CharSequence cs, int start, int before, int count) {

        MainActivity.this.adapter.getFilter().filter(cs);

        }

});

I can't figure out the problem since it's working fine with other characters.


Solution

  • Try using trim(). Hope it will work for you.I know you will need to modify this code.but it may give you some idea.

    search.addTextChangedListener(new TextWatcher(){
    
        @Override
        public void afterTextChanged(Editable arg0) {
            // TODO Auto-generated method stub
    
            MainActivity.this.adapter.getFilter().filter(search.getText().toString().trim());
    
        }
    
        @Override
        public void beforeTextChanged(CharSequence arg0, int arg1,
                int arg2, int arg3) {
            // TODO Auto-generated method stub
    
        }
    
        @Override
        public void onTextChanged(CharSequence cs, int start, int before,
                int count) {
            // TODO Auto-generated method stub
    
            }
    
    });
    

    If this doesnt work try second option

    search.addTextChangedListener(new TextWatcher(){
    
        @Override
        public void afterTextChanged(Editable arg0) {
           String result = s.toString().replaceAll(" ", "");
        if (!s.toString().equals(result)) {
             ed.setText(result);
             ed.setSelection(result.length());
             // alert the user
        }
    
        }
    
        @Override
        public void beforeTextChanged(CharSequence arg0, int arg1,
                int arg2, int arg3) {
            // TODO Auto-generated method stub
    
        }
    
        @Override
        public void onTextChanged(CharSequence cs, int start, int before,
                int count) {
    
    
            }
    
    });
    

    I prefer first option using trim() to string text.