Comparing string typed with string in database

0
Hello, I'm doing a job ... of an app in android in 3 layers ... and it's an evaluation app for bars and lancherias ... that consists of getting the name of the place ... the address. the email and the evaluation ... but I'm having a difficulty ... I want to get the location to compare if the location typed already exists in the database and not let it enter again.

But when I try to do this ... my method does not work ... it closes or inserts normally ... the method is this

This is the libClass

public class Local {

    private int id;
    private String local;
    private String endereco;
    private String email;
    private String telefone;
    private Float avaliacao;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getLocal() {
        return local;
    }

    public void setLocal(String local) {
        this.local = local;
    }

    public String getEndereco() {
        return endereco;
    }

    public void setEndereco(String endereco) {
        this.endereco = endereco;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getTelefone() {
        return telefone;
    }

    public void setTelefone(String telefone) {
        this.telefone = telefone;
    }

    public Float getAvaliacao() {
        return avaliacao;
    }

    public void setAvaliacao(Float avaliacao) {
        this.avaliacao = avaliacao;
    }
}

This is the button method that adds:

public void adicionar(View v) {

    if (editLocal.getText().toString().trim().isEmpty()) {

        editLocal.setError("Coloque um Local!");
    } else {
        if (editEndereco.getText().toString().trim().isEmpty()) {

            editEndereco.setError("Coloque um Endereço");
        } else {
            if (editTelefone.getText().toString().isEmpty()) {

                editTelefone.setError("Coloque um Telefone!");

            } else {

                Local local = new Local();

                local.setId(0);
                local.setLocal(editLocal.getText().toString());
                local.setEndereco(editEndereco.getText().toString());
                local.setEmail(editEmail.getText().toString());
                local.setTelefone(editTelefone.getText().toString());
                local.setAvaliacao(ratingBarNota.getRating());

                LocalBLL localBLL = new LocalBLL(getApplicationContext());

                Utilidades util = new Utilidades();

                //aqui começa a comparacao
                nomeLocal = editLocal.getText().toString();

                compara = localBLL.comparaLocais(nomeLocal);

                if (compara == 1) {

                    util.exibirToast(getApplicationContext(), "Local já Cadastrado!");

                } else {

                    try {

                        localBLL.insertLocal(local);
                        util.exibirToast(getApplicationContext(), "Você Salvou um Local!");

                        popularListView();
                        cancelar();

                    } catch(Exception ex) {

                        util.exibirToast(getApplicationContext(), getExternalCacheDir().toString());

                    }
                }

            }
        }
    }
}

And this is the libBLL method:

public int comparaLocais(String nomeLocal) {

    LocalDAL localDAL = new LocalDAL(context);

    Local local = null;

    return localDAL.comparaLocal(nomeLocal);

}

And this is the libDAL method:

public int comparaLocal(String nomeLocal) {

    String SELECT_LOCAISCOMPARACAO = "SELECT * from locais where nome_local ='" + nomeLocal + "'";

    BancoDados banco = new BancoDados(context);

    SQLiteDatabase db = banco.getReadableDatabase();

    Cursor cursor = db.rawQuery(SELECT_LOCAISCOMPARACAO, null);

    Local local = null;

    if (cursor.moveToFirst()) {

        local = new Local();

        do {

            local.setId(cursor.getInt(0));
            local.setLocal(cursor.getString(1));
            local.setEndereco(cursor.getString(2));
            local.setEmail(cursor.getString(3));
            local.setTelefone(cursor.getString(4));
            local.setAvaliacao(cursor.getFloat(5));

        } while ( cursor . moveToNext ());

    }

    comparacao = local.getLocal();

    if (nomeLocal == comparacao) {

        return 1;

    } else {

        return 0;

    }

}

In my opinion ... it was to be working ... I'm a beginner on Android ... so if you guys can help me thank you very much ... I'm breaking my head kk to my view the variable compares does not receive the value of local.getlocal ();

Thanks, if anyone knows right away The error in logcat is that of androidstudio is this:

    
asked by anonymous 19.10.2016 / 20:34

2 answers

2

In Java the == operator does not test for the equality of the contents of String , ie, it is not a test of equality of values of each string itself, but a test of equality of references of each variable ( refer, or "point", to the same memory address).

  • == : Tests for equality of references
  • .equals() : Tests for equality of values (or content)

Switch to:

if (nomeLocal.equalsIgnoreCase(comparacao)) {
   return 1;
} else {
   return 0;
}

I used equalsIgnoreCase() because I imagine it's your intention to ignore differences in the box (uppercase vs. lowercase).

To make it clearer:

String str1 = "Loudenvier";
String str2 = str1;
String str3 = "Loudenvier";

str1 == str2; // (verdadeiro: são a mesma referência)
str1 == str3; // (falso: são referências diferentes (depende do otimizador))
str2 == str3; // (falso: idem)
str3.equals(str1); // (verdadeiro: têm o mesmo conteúdo)
str2.equals(str1); // (verdadeiro: têm o mesmo conteúdo, afinal ambas referenciam a mesma posição de memória)

Long explanation:

Excluding primitive types, all other variables in Java do not, in themselves, hold the value, or rather content themselves. In fact they "point" or refer to their own value, which is stored elsewhere in memory. In other languages, usually of lower level (such as C and C ++), this means that the variables in Java are pointers ( pointers ) typed. The language syntax makes "pointer" operations (which generate so much headache in other languages) trivial to automatically the contents of the variables, without introducing a specific syntax for it.

The String in Java is not a primitive type, but a referenced type, so the == comparator checks if two variables refer to the same "address" memory. If they have the same content but different memory addresses, the == comparator will return false. Since the equals method (and the very useful equalsIgnoreCase ) compares the content itself of each string, checking all the characters to return true if they are equal, or false, otherwise.

    
19.10.2016 / 20:40
0

The error is happening because you are initializing the "local" object only if the query brings data, if it does not bring you, it never initializes it and therefore it always stays as "null", before the comparison add a validation to it

if (local != null) {
// faça a comparação
} else {
// retorne informando que o local não existe, no seu caso "return 0"
}

Now about checking if it is the same, do not compare Strings with "==", although the names are visually equal, internally Java can understand that they are different things, as a rule, always use equals () or equalsIgnoreCase ()

link to a great post about strings comparison.

link

Ex of comparisons.

String nome = "Thiago";

if (nome.equals("Thiago")) {
// retorno verdadeiro
} 

if (nome.equals("thiago")) {
// retorno falso
}

if (nome.equalsIgnoreCase("Thiago")) {
// retorno verdadeiro
} 

if (nome.equalsIgnoreCase("thiago")) {
// retorno verdadeiro
}

Edit: So, by joining the two answers and following the line of your program, it should look like the code below

Local local = null;

if (cursor.moveToFirst()) {

    local = new Local();

    do {

        local.setId(cursor.getInt(0));
        local.setLocal(cursor.getString(1));
        local.setEndereco(cursor.getString(2));
        local.setEmail(cursor.getString(3));
        local.setTelefone(cursor.getString(4));
        local.setAvaliacao(cursor.getFloat(5));

    } while ( cursor . moveToNext ());

}

if (local != null) {
    comparacao = local.getLocal();

    if (nomeLocal.equalsIgnoreCase(comparacao)) {
        return 1;
    } else {
        return 0;
    }
} else {
    return 0;
}
    
19.10.2016 / 20:48