Search randomly in listview through editext on android?

Asked

Viewed 766 times

0

Hello, I’m very new in programming, actually enthusiastic, look at me I’m kind of editext search the letter or word in the text so that for example if in my string is written "Mr. Jose Ventura" and I type only "Ventura" this can be located. Thanks in advance, I am grateful to post the 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. José Ventura","Sra. Maria Cícera","Vô Antonio"};


    lv.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, lst));
    CarregarEncontrados();


    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.
        }


        public void onTextChanged(CharSequence s, int start, int before, int count)
        {
            CarregarEncontrados();


            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. José Ventura")){
                test.setTitle("test1");
                test.setMessage("0123456789");
                test.setNeutralButton("OK", null);
                test.show();


            }
            if(((TextView) view).getText().equals("Sra. Maria Cícera")){
               test.setTitle("Sra. Maria Cícera");
                test.setMessage("486597231");
                test.setNeutralButton("OK", null);
                test.show();
            }

            if(((TextView) view).getText().equals("Vô Antonio")){
                test.setTitle("Vô Antonio");
                test.setMessage("23456892");
                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();


            textoAux = removeAcentos(textoAux);

            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');
        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();

}
  • What’s your problem? What did you try to do?

  • So, sir. Jorge B. I don’t know how to use the vocubulario de vcs usuarios Vanzados, but I’ll explain to you, this code is up there working blza, only what kind in my string has written "Mr. Jose Ventura" if I just type "Ventura" in the edittex no "Mr. Jose Ventura" on the list, so what I’m looking for is something that can cause even if I type words or letters that are in the middle of the sentences or words these can be shown in the search. I could tell?

2 answers

0


Simply on my loadable found I changed the code by this and so it does searches between words, hope to help:

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

    lst_Encontrados.clear();

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

            if (lst[i].toLowerCase().contains(
                    et.getText().toString().toLowerCase().trim())) {
                lst_Encontrados.add(lst[i]);
            }
        }
    }
}

0

Wilfer, I did something similar to this these days, it’s a filter that lets you search by typing inside an Edittext.

This method you add inside your Adapter.

public Filter getFilter()
{
    Filter filter = new Filter()
    {
        @Override
        protected FilterResults performFiltering(CharSequence filtro)
        {
            FilterResults results = new FilterResults();

            if (filtro == null || filtro.length() == 0)
            {
                results.count = listaProfdFiltrado.size();
                results.values = listaProfdFiltrado;
            } else
            {
                List<Produto> produtosFiltrados = new ArrayList<Produto>();

                for (int i = 0; i < listaProfdFiltrado.size(); i++)
                {
                    Produto produto = listaProfdFiltrado.get(i);

                    filtro = filtro.toString().toLowerCase();
                  //condicao, ean e plu alterar para os itens que deseja buscar
                    String condicao = produto.getDescricao().toLowerCase();
                    String ean = produto.getEan();
                    String codigoPlu = produto.getCodigo();
                   //apenas uma validação minha porque preciso buscar por 3 referencias
                    if (condicao.contains(filtro) || ean.contains(filtro) || codigoPlu.contains(filtro))
                    {

                        produtosFiltrados.add(produto);

                    } 
                }

                results.count = produtosFiltrados.size();
                results.values = produtosFiltrados;

            }
            return results;
        }

        @SuppressWarnings("unchecked")
        @Override
        protected void publishResults(CharSequence constraint, Filter.FilterResults results)
        {
            listaProdutos = (List<Produto>) results.values;

            notifyDataSetChanged();
        }

    };
//retorna o filter do que você pesquisou
    return filter;

}

Inside your onCreate you need to initialize your component, the onTextChanged method is responsible for displaying the changes you make when you type.

   EditText editText = (EditText) findViewById(R.id.editText1);
    editText.addTextChangedListener(new TextWatcher()
    {
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count)
        {
            //o filtro é chamado para efetuar as operações
            adapterListView.getFilter().filter(s.toString());
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after)
        {
        }

        @Override
        public void afterTextChanged(Editable s)
        {
        }
    });

Note: These lists are for my use, you need to switch to either a simple array or work with your list type.

Documentation where it deals with Filter

  • I will try here to see if I understand what you wrote above, see only I will have to write your public filter below my code or I will have to create an Adapter class just for him? Thanks and a thousand apologies since I am a programming enthusiast, do not get a course or something like that or I live like this I go on the basis of error and hit and talking to you here! thank you so much for the help from now! and trying to understand what is written to adapt my need!

  • 1

    I do not know how is your project, it would be ideal to have an Adapter, but if you have not yet reached this level below the code, give a look at the android blogs a lot has examples of small but complete applications for you to train, I also point out the book of Lecheta - Google Android, when I started he was with me for coffee, lunch and dinner. Any questions put here. @wilfer

  • Wellington Avelino, I’m still a beginner, but some things I can understand some not, I understand about programming logic, but language itself costs me a little, so Adapter I have an idea of how to do, but I will do as Oce ordered and see what the!

  • I tried to copy and put below my code, some things knew how to change the names already others does not follow below what I could not change:

  • List<Product> productsFilted = new Arraylist<Product>(); not why my attribute should change the word"product" Product = lst_Encontrados.get(i); and not the word getdescricao String condicao = product.getDescription(). toLowerCase(); and to getean and also to getCodigo, thank you very much

  • I just defined that the filtered products will be a list of products

  • Uhum I think your answer is great and solve my problem, pity that I am not able to understand the logic of how to implement your code as my, thank you very much friend for the help! May all be well as you and loved ones always!

  • If it’s not too much trouble for your person, could you help me a little more, like implement your code in my code and copy here? BS: I know you must obviously be busy, I will gladly keep your help.

Show 3 more comments

Browser other questions tagged

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