Filter Edittext from listview on android

Asked

Viewed 1,024 times

1

I’m making this code that’s running blaza, but there’s a problem, in my string it’s written "Mr. Jose Ventura" then when I type only "Jose" or just "Ventura" nothing appears in the search, could someone implement this in my code?

public class MainActivity extends ActionBarActivity {
private ListView lv;
private EditText et;
private String[] lst;
private ArrayList<String> lst_Encontrados = new ArrayList<String>();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    lv = (ListView) findViewById(R.id.lvlist);
    et = (EditText) findViewById(R.id.etlist);

    lst = new String[] {"Sr. Jose Ventura","Sra. Viviana Araujo","Sr. Mario Jorge"};

    //Carrega o listview com todos os itens
    lv.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, lst));
    CarregarEncontrados();

    //Adiciona um TextWatcher ao TextView cujos métodos são chamados sempre
    //que este TextView sofra alterações.
    et.addTextChangedListener(new TextWatcher()
    {
        public void afterTextChanged(Editable s)
        {
            // Abstract Method of TextWatcher Interface.
        }

        public void beforeTextChanged(CharSequence s, int start, int count, int after)
        {
            // Abstract Method of TextWatcher Interface.
        }

        //Evento acionado quando o usuário teclar algo
        //na caixa de texto "Procurar"
        public void onTextChanged(CharSequence s, int start, int before, int count)
        {
            CarregarEncontrados();

            //Carrega o listview com os itens encontrados
            lv.setAdapter(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, lst_Encontrados));
        }
    });

    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> arg0, View view, int position, long id) {


            AlertDialog.Builder test = new AlertDialog.Builder(MainActivity.this);

            if(((TextView) view).getText().equals("Sr. Jose Ventura")){
                test.setTitle("Doido");
                test.setMessage("doidera");
                test.setNeutralButton("OK", null);
                test.show();


            }
            if(((TextView) view).getText().equals("Sr. Mario Jorge")){
                test.setTitle("Vizinho");
                test.setMessage("kct");
                test.setNeutralButton("OK", null);
                test.show();
            }

            if(((TextView) view).getText().equals("Sra. Viviana Araujo")){
                test.setTitle("eu");
                test.setMessage("louquinha");
                test.setNeutralButton("OK", null);
                test.show();;;
            }


        }
    });



}


public void CarregarEncontrados() {
    int textlength = et.getText().length();

    lst_Encontrados.clear();

    for (int i = 0; i < lst.length; i++) {
        if (textlength <= lst[i].length()) {

            String textoAux = (String) lst[i].subSequence(0, textlength);
            String textoFormatado = et.getText().toString();

            //Removendo acentos do item da lista a comparar
            textoAux = removeAcentos(textoAux);
            //Removendo acentos do item digitado
            textoFormatado = removeAcentos(textoFormatado);
            if (textoFormatado.equalsIgnoreCase(textoAux)) {
                lst_Encontrados.add(lst[i]);

            }
        }
    }
}
private static Map<Character, Character> acentosMap;

public static String removeAcentos(String texto) {

    if (acentosMap == null || acentosMap.size() == 0) {
        acentosMap = new HashMap<>();
        acentosMap.put('À', 'A');
        acentosMap.put('Á', 'A');
        acentosMap.put('Â', 'A');
        acentosMap.put('Ã', 'A');
        acentosMap.put('Ä', 'A');
        acentosMap.put('È', 'E');
        acentosMap.put('É', 'E');
        acentosMap.put('Ê', 'E');
        acentosMap.put('Ë', 'E');
        acentosMap.put('Í', 'I');
        acentosMap.put('Ì', 'I');
        acentosMap.put('Î', 'I');
        acentosMap.put('Ï', 'I');
        acentosMap.put('Ù', 'U');
        acentosMap.put('Ú', 'U');
        acentosMap.put('Û', 'U');
        acentosMap.put('Ü', 'U');
        acentosMap.put('Ò', 'O');
        acentosMap.put('Ó', 'O');
        acentosMap.put('Ô', 'O');
        acentosMap.put('Õ', 'O');
        acentosMap.put('Ö', 'O');
        acentosMap.put('Ñ', 'N');
        acentosMap.put('Ç', 'C');
        acentosMap.put('ª', 'A');
        acentosMap.put('º', 'O');
        acentosMap.put('§', 'S');
        acentosMap.put('³', '3');
        acentosMap.put('²', '2');
        acentosMap.put('¹', '1');
        acentosMap.put('à', 'a');
        acentosMap.put('á', 'a');
        acentosMap.put('â', 'a');
        acentosMap.put('ã', 'a');
        acentosMap.put('ä', 'a');
        acentosMap.put('è', 'e');
        acentosMap.put('é', 'e');
        acentosMap.put('ê', 'e');
        acentosMap.put('ë', 'e');
        acentosMap.put('í', 'i');
        acentosMap.put('ì', 'i');
        acentosMap.put('î', 'i');
        acentosMap.put('ï', 'i');
        acentosMap.put('ù', 'u');
        acentosMap.put('ú', 'u');
        acentosMap.put('û', 'u');
        acentosMap.put('ü', 'u');
        acentosMap.put('ò', 'o');
        acentosMap.put('ó', 'o');
        acentosMap.put('ô', 'o');
        acentosMap.put('õ', 'o');
        acentosMap.put('ö', 'o');
        acentosMap.put('ñ', 'n');
        acentosMap.put('ç', 'c');
    }

    if (texto == null) {
        return "";
    }

    StringBuilder sb = new StringBuilder(texto);

    for (int i = 0; i < texto.length(); i++) {
        Character c = acentosMap.get(sb.charAt(i));
        if (c != null) {
            sb.setCharAt(i, c);
        }
    }

    return sb.toString();

}
  • Yes wellingto Avelino, I decided to just change the theme of the question and put the full code, because I could not implement its answer, which I believe is very effective but complex for me.

  • I recommend Edit your question in these cases @wilfer

  • ah, thanks @Wellingtonavelino!

1 answer

1


In that part of your code:
lv.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, lst));
it is better to use a variable and use the Arrayadapter getfilter method, making this change your code would look like this:

 ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, lst_Encontrados);
 lv.setAdapter(adapter);

And in the addTextChangedListener method you manipulate the results from the Adapter and not from Listview and putting the Adapter inline would be impossible to use it that way:

 et.addTextChangedListener(new TextWatcher() {

        @Override
        public void afterTextChanged(Editable arg0) {
            // TODO Auto-generated method stub
        }

        @Override
        public void beforeTextChanged(CharSequence arg0, int arg1,
                                      int arg2, int arg3) {
            // TODO Auto-generated method stub
        }

        @Override
        public void onTextChanged(CharSequence arg0, int arg1, int arg2,
                                  int arg3) {
            // TODO Auto-generated method stub
            if (adapter != null) {
                adapter.getFilter().filter(arg0.toString());
            }
            if (arg0.toString().equals("")) {
                adapt.notifyDataSetChanged();
            }
        }

    });

This way it is not necessary to filter using its created method, using only a function of the Arrayadapter itself.

  • Friend I tried here, I typed the same as Voce typed, I didn’t even copy and paste hahaha, see only now do not search the words the rest works, thank you very much for the help

  • I gave an edited answer, so you can search after the spaces, but it will not be possible to search inside a word, for example: "ose", or "entura", and whenever your text is empty, it will return the list in the original form

Browser other questions tagged

You are not signed in. Login or sign up in order to post.