CPF validation on Android - Arraylist error

Asked

Viewed 1,678 times

2

I have this class to validate CPF field on android, however is giving error in line: ArrayList<Separador> posicaoSeparadoresTexto(String mascara)

Follow below full code:

package com.mcavalini.lib;

import java.util.ArrayList;

public class Utils {

    public static int tamanhoMaximo(String mascara) {
        String novaString = removeCaracteresEspeciais(mascara);
        return novaString.length();
    }

    public static String removeCaracteresEspeciais(String str) {

        String[] caracteresEspeciais = {"\\.", ",", "-", ":", "\\(", "\\)", "ª", "\\|", "\\\\", "°", "\\/"};

        for (int i = 0; i < caracteresEspeciais.length; i++) {
            str = str.replaceAll(caracteresEspeciais[i], "");
        }

        return str;
    }

    public static ArrayList<Separador> posicaoSeparadoresTexto(String mascara) {
        ArrayList<Separador> listaSeparadores = new ArrayList<Separador>();

        for (int i = 0; i < mascara.length(); i++) {
            if ( (mascara.substring(i, i+1).equals(new String(","))) ||
                 (mascara.substring(i, i+1).equals(new String("."))) ||
                 (mascara.substring(i, i+1).equals(new String("-"))) ||
                 (mascara.substring(i, i+1).equals(new String("/"))) ||
                 (mascara.substring(i, i+1).equals(new String("("))) ||
                 (mascara.substring(i, i+1).equals(new String(")")))) {
                listaSeparadores.add(new Separador(new Integer(i), mascara.substring(i, i+1)));
            }
        }

        return listaSeparadores;
    }

    public static String padString(String numero, int tamanhoMaximo, int tamanhoMascara, ArrayList<Separador> listaSeparadores) {
        String stringMascarada = "";
        boolean isPad = true;
        int indicePadString = 0;
        int indiceNumero = 0;
        int tamanhoNumero = numero.length();

        while (isPad) {
            for (Separador separador : listaSeparadores) {
                if (separador.getPosicao().intValue() == indicePadString) {
                    stringMascarada += separador.getCaracter();
                    indicePadString += 1;
                    break;
                }
            }

            if ((indiceNumero < tamanhoMaximo) && (indiceNumero < tamanhoNumero) ) {
                stringMascarada += numero.substring(indiceNumero, indiceNumero+1);
            } 

            indicePadString += 1;
            indiceNumero += 1;

            if (indiceNumero >= tamanhoNumero)
                isPad = false;
        }

        return stringMascarada;
    }
}

package com.mcavalini.lib;

import android.text.InputType;
import android.text.method.NumberKeyListener;

public class KeyListenerNumber extends NumberKeyListener {

    public int getInputType() {
        return InputType.TYPE_CLASS_NUMBER | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS;
    }

    @Override
    protected char[] getAcceptedChars() {
        return new char[] {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
    }

}

package com.mcavalini.core;

import android.content.Context;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.widget.EditText;

import com.mcavalini.lib.KeyListenerNumber;
import com.mcavalini.lib.Utils;

public class MaskEditText extends EditText {
    private String mascara;
    private int tamanhoMascara;
    private int tamanhoMaximo;

    private boolean isUpdating;

    private KeyListenerNumber keyListenerNumber;

    public static String CPF_MASK = "   .   .   -  ";
    public static String CEP_MASK = "     -   ";
    public static String TELEFONE_8DIGITOS_MASK = "(  )    -    ";

    public MaskEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
    }   

    public int getTamanhoMascara() {
        return tamanhoMascara;
    }

    public void init(String mascara) {
        this.mascara = mascara;
        this.tamanhoMascara = mascara.length();
        this.tamanhoMaximo = Utils.tamanhoMaximo(mascara);

        keyListenerNumber = new KeyListenerNumber();
        this.setKeyListener(keyListenerNumber);
        this.setText("");

        this.addTextChangedListener(new TextWatcher() {

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

            }

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

            }

            public void afterTextChanged(Editable s) {
                String stringAtual = s.toString();

                if (isUpdating) {
                    isUpdating = false;
                    return;
                }

                String numero = stringAtual.replaceAll("[^0-9]*", "");

                if (numero.length() > tamanhoMaximo)
                    numero = numero.substring(0, tamanhoMaximo);

                String campo = Utils.padString(numero, tamanhoMaximo, tamanhoMascara, Utils.posicaoSeparadoresTexto(MaskEditText.this.mascara));

                isUpdating = true;

                MaskEditText.this.setText(campo);
                MaskEditText.this.setSelection(campo.length());
            }
        });
    }
}

    <com.mcavalini.core.MaskEditText
        android:id="@+id/txtCpf"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" >
        <requestFocus />   
    </com.mcavalini.core.MaskEditText>
  • What’s the mistake ?

  • Cannot solve Symbol Separator

  • And where does this class come from Separador?

  • I took this example ready from: http://www.guj.com.br/java/281645-mascara-no-edittext-do-android

  • The problem is that the class Separador is not defined anywhere. If you go to the page of the site from where you removed the code, there is an entry from someone who asks a question on the subject and got no answer. Without this class the code does not compile.

  • 1

    Okay, thank you all for your help.

  • I am voting to close this question because the problem (lack of class Separador) has already been identified by AP, is punctual and would hardly help other people in the community.

  • @Luizvieira Do not close. This class is easy to provide. I am writing an answer now.

  • @Victor Cool you have provided the class. But still this question seems unapproachable to me, don’t you think? You had to interpret the whole AP code for infer what the class would be like Separador, where the need for it (validate CPF) could be realized in numerous other ways perhaps simpler and without the potential problems that you yourself cite in your answer. Anyway, I really wonder if this question has the potential to help anyone beyond the AP...

  • @Luizvieira If the AP found this code in the GUJ, decided to try and had a problem, then I believe that the same could happen to more people. And people who google CPF validation on android will find this question and the GUJ too. Besides, if anyone can give a better answer than mine, I don’t see why not. However, I agree that the question is not a very good one, but I still find it salvageable. And I also agree that there are much better ways to validate a CPF on android, and look at this, someone could post this as an answer!

  • 1

    @Victor I understand your points. Anyway, if it’s a mistake, I prefer to do it for the sake of content and AP. So I withdrew my vote to close. Let’s see if the question improves. :)

Show 6 more comments

1 answer

0


As already said in the comments, is missing the class Separador. Let’s design this class:

public class Separador {
    private final Integer posicao;
    private final String caracter;

    public Separador(Integer posicao, String caracter) {
        this.posicao = posicao;
        this.caracter = caracter;
    }

    public Integer getPosicao() {
        return posicao;
    }

    public String getCaracter() {
        return caracter;
    }
}

And with that, your code should compile and work.


However, the code still has several other problems:

  • It does not use autoboxing and autounboxing properly, using new Integer(i) instead of just i and then using the getPosicao().intValue() rather than simply getPosicao().

  • The class Separador I put up was made to be compatible with the code, but it could be better if posicao were int and not Integer and caracter were char and not String, but for that would have to change the class Utils.

  • Utilise new String(",") is unnecessary, enough ",".

  • Use as type ArrayList<Separador> instead of List<Separador> is not a good practice, goes against the principle code to an interface.

  • The presence of a class called Utils full of static methods appears to be some deeper anti-pattern.

  • There must be other problems yet.

Browser other questions tagged

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