How to ignore the accents in Listview on Android?

Asked

Viewed 376 times

4

I was making an app for me kind of joking around and I came across a problem, the ListView Android Studio does not ignore the accents of Portuguese.

Could someone post a code to fix this? Like do the word search by ignoring the accents.

Follow the code I’m using below.

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[] {
            "Cáncer", "Cancer", "Mamá"
        };

        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("Cáncer")) {
                    test.setTitle("hemoglobina");
                    test.setMessage("doidera");
                    test.setNeutralButton("OK", null);
                    test.show();
                }

                if (((TextView) view).getText().equals("Cancer")) {
                    test.setTitle("Volume");
                    test.setMessage("KCT");
                    test.setNeutralButton("OK", null);
                    test.show();
                }

                if (((TextView) view).getText().equals("Mamá")) {
                    test.setTitle("eu");
                    test.setMessage("sou fodastico");
                    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()) {
                if (et.getText().toString().equalsIgnoreCase((String) lst[i].subSequence(0, textlength))) {
                    lst_Encontrados.add(lst[i]);
                }
            }
        }
    }
}

1 answer

4


If you are in API 9 or higher, you can use a simple method with Normalizer and a REGEX to remove all accents. If not, you will need to create a Map with the accents and change them.

Try something similar:

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 void removeAcentos(String texto){
    //Verificando a versão do SDK instalado no device
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
        removeAcentosPosGingerbread(texto);
    } else {
        removeAcentosPreGingerbread(texto);
    }
}

@TargetApi(Build.VERSION_CODES.GINGERBREAD)
public String removeAcentosPosGingerbread(String texto) {
    //Fazendo a troca dos caracteres acentuados pelos correspondentes nao acentuados
    texto = Normalizer.normalize(texto, Normalizer.Form.NFD);

    //Removendo as "sujeiras" deixadas no processo
    texto = texto.replaceAll("[^\\p{ASCII}]", "");

    return texto;
}

private static Map<Character, Character> acentosMap;

public static String removeAcentosPreGingerbread(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();

}
  • Thanks for the tip buddy, I tried to copy and paste your code, but I am using API 8 and android studio tells me that Normalizer only works on API 9, even so thank you.

  • @wilfer hello. I edited the answer, see if it now works!

  • Hello, thanks again for the tip, sorry to be a bit boring, but as I said I’m just curious in programming, what would be the method to initialize the string "removeAcentosPreGingerbread", thanks in advance. PS: I am looking for books, videos and giving a study in android programming on the net, since I do not count on courses or something similar in my region.

  • @wilfer edited again. The code you quoted, is for checking the SDK installed on the device. Depending on the version, call the specific method for each one

  • Thanks a lot, @sicachester, it worked just fine. Valeuzaoo.

Browser other questions tagged

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