Comparing typed string with string in database

Asked

Viewed 739 times

0

hello, I’m doing a work ... of an android app in 3 layers ... and it’s a review app for bars and snacks ... which consists of taking the name of the place ... the address .. the email and the evaluation ... however I am with a difficulty ... I want that when picking up the location it has to compare if the typed location is already existing to the database and not let it enter again.

but when I try to do that ... my method is not right ... 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 method of the button 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 that’s the way of libBLL:

public int comparaLocais(String nomeLocal) {

    LocalDAL localDAL = new LocalDAL(context);

    Local local = null;

    return localDAL.comparaLocal(nomeLocal);

}

And that’s the way of libDAL:

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 view ... it was supposed to be working ... I’m beginner in Android ... so if you can help me thank you very much ... I’m breaking my head kk to see the variable compare does not get the value of local.getlocal();

I’d appreciate it if someone knew right away The bug in logcat is this from androidstudio is this:

inserir a descrição da imagem aqui

2 answers

2

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

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

Change to:

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

I used the equalsIgnoreCase() because I imagine it is 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 the other variables in Java do not keep their own value, or rather their own content. In fact they "point out", or refer to their own value, which is stored elsewhere in memory. In other languages, usually at a lower level (such as C and C++), this means that variables in Java are pointers (pointers) typed. Language syntax makes "pointer" operations (which generate so much headache in other languages) trivial to dereference automatically the contents of the variables, without entering a specific syntax for this.

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

0

The Error is happening because you are initiating the "local" object only if the query brings data, if it does not bring you never initialize it and therefore 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 equal, 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 the equals() or equalsIgnoreCase functions()

link to a great post about Strings comparison.

/a/3954/57900

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;
}
  • Hello ... I appreciate the help however, the error persists ... I did as you spoke loudenvier ... and as Voce said Thiago .. but the error is the same ... it seems to me that the variable compares not taking the value of local.getlocal .... I used the equalsingnorecase and it stops when it arrives in this part ... and the equals normal tbm ... was thus the code

  • 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 (nameLocal.equalsIgnoreCase(comparison)) { Return 1; }Else { Return 0; }

  • puts ... was left without indentation the code ... for the apology...

  • the code did not fit here ... but anyway .. only was placed the ignore case and the error persists ... if you can help thank you

  • @Loudenvier exists but some command I take the information and put inside the variable to compare ? ... I guess it’s not working out that way

  • I understood what you said ... just do not know how to put here ... can give an example of how it would be right ?

  • @Filipe see my answer, I edited it and added a more complete answer of how your code should look, adapt it in your program and see resolve.

  • thank you so much for the help ... as I said I’m starting to develop ... and my mistake was from logica msm ... I speak only that Lse at the end there to work ... thank you so much for your help ... vlw msm

  • @Loudenvier thanks to you too ... helped me a lot! vlw msm

Show 4 more comments

Browser other questions tagged

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