Select and calculate columns - SQLite

1

Hello ...

//selecionar valores da tabela:

    public Cursor IMC(){
            Cursor cursor;
            String[] campos =  {"SELECT (peso/(altura*altura)) FROM medidas WHERE codigo = (SELECT codigo FROM medidas ORDER BY codigo DESC LIMIT 1)"};

            db = banco.getReadableDatabase();

            cursor = db.query("medidas", campos, null, null, null, null, null, null);

            if(cursor!=null){
                cursor.moveToFirst();
            }
            db.close();
            return cursor;
        }

In SQLExpert SELECT looking for only one column or a simple operation as weight + height works fine, however this in the above code returns 0. I have already noticed that you are creating the database and saving the values.

//mostrar o resultado do SELECT em um TextView
public void resultadoIMC() {

                BancoController crud = new BancoController(getBaseContext());
                Cursor cursor = crud.IMC();


                TextView tv = (TextView) findViewById(R.id.txtresultado_imc);

                tv.setText(cursor.getString(cursor.getColumnIndex(String.valueOf(0))));


            }

In this code does not return any value, even changing the SELECT to fetch the value of a single column (In SQLExpert the SELECT works).

Does anyone have any idea what's wrong ???

    
asked by anonymous 02.12.2016 / 15:50

1 answer

1
//você precisa abrir a conexão antes
db = banco.getReadableDatabase();

//salvando a query antes. Eu NÃO conferi se a query está correta
//só coloquei a maneira certa de fazer um SELECT
String query =  "SELECT (peso/(altura*altura)) FROM medidas WHERE codigo = (SELECT codigo FROM medidas ORDER BY codigo DESC LIMIT 1)";

//usando rawQuery, que é o correto
Cursor cursor = db.rawQuery(query,null);
    
02.12.2016 / 16:08