Query with android sqlite java filter

Asked

Viewed 504 times

2

public ArrayList<Contato> filtrar(String filtro) {
    ArrayList<Contato> contatoArray = new ArrayList<>();

    //Consulta que traz todos dados de todas colunas
    Cursor cursor = database.query(BaseDAO.TABELA_AGENDA, BaseDAO.COLUNAS_TABELA_AGENDA, null, null, null, null, BaseDAO.CONTATO_NOME);

    cursor.moveToFirst();
    while(!cursor.isAfterLast()) {

        Contato c = new Contato();

        if (cursor.getString(1).equalsIgnoreCase(filtro) || cursor.getString(3).equalsIgnoreCase(filtro)) {
            c.setId(cursor.getInt(0));
            c.setNome(cursor.getString(1));
            c.setTelefone(cursor.getString(2));
            c.setEmpresa(cursor.getString(3));
            c.setBrunko(cursor.getInt(4) == 1);
            c.setCarter(cursor.getInt(5) == 1);
            c.setFortmetal(cursor.getInt(6) == 1);
            c.setNdflex(cursor.getInt(7) == 1);
            c.setNotus(cursor.getInt(8) == 1);
            c.setMerco(cursor.getInt(9) == 1);
            c.setMetan(cursor.getInt(10) == 1);
            c.setRiosulense(cursor.getInt(11) == 1);
            c.setYming(cursor.getInt(12) == 1);
            c.setMesContato(cursor.getInt(13));
            c.setAnoContato(cursor.getString(14));

            contatoArray.add(c);
        }
        cursor.moveToNext();
    }
    cursor.close();
    return contatoArray;
}

My code is apparently correct with the Log.d() I got the values of filtro, cursor.getString(1) and cursor.getString(3) which are the same, for example "Name Test", "Name Test" and "Company Test", but they do not enter the if() what is wrong?

  • 1

    Add a watch in the conditionals: cursor.getString(1). equalsIgnoreCase(filter) and cursor.getString(3). equalsIgnoreCase(filter). The two must be returning false.

  • Please put a Log print with the 3 values: cursor.getString(1), cursor.getString(3) and filtro. The ideal was even the print of watch in Debug so that you can be sure of the contents of the fields/variables. In debug you can see the Bugger going over if when you see these values?

2 answers

2


By Log I realized that the registered variables were gaining a space at the end of them so a variable "x" for example was "x", so it did not work the if()

  • Are you offering a reward yet, or have you found an answer that is efficient?

1

You should put the filter in the query and then remove the condition if. Something like:

Cursor cursor = database.query(BaseDAO.TABELA_AGENDA, BaseDAO.COLUNAS_TABELA_AGENDA, "coluna1 = ? or coluna3 = ?", new String[]{filtro, filtro}, null, null, BaseDAO.CONTATO_NOME);
  • the problem is that this is just a small piece of the query that has more than 400 lines, in case are several if with several options according to what the sending user in the variable filtro, only this if does not work all other yes

Browser other questions tagged

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