Display given in textView

Asked

Viewed 352 times

1

I have a database in an application of android, would like the name field in the table, fill the text of TextView. I saw some examples but I couldn’t implement, the getReadableDatabase().rawQuery(sqlNome, null); is always in red, that is, I cannot use it. It is only a data that will be in the table.

Follow the code I tried to implement:

criaBanco = new CriaBanco(getBaseContext());
sqlNome = "select nome from tabela";
Cursor cursor = getReadableDatabase().rawQuery(sqlNome, null);

textView = (TextView) findViewById(R.id.txt1);
if (!criaBanco.NOME.isEmpty()) {
    textView.setText(sqlNome);
}
else {
    textView.setText("NOME");
}

cursor.close();
  • 2

    Won’t be Cursor cursor = criaBanco.getReadableDatabase().rawQuery(sqlNome, null);?

  • 1

    @ramaral vc is correct. thanks. Put as an answer so you can mark it and put 1 vote.

2 answers

1

Good morning Henrique, The method getReadableDatabase() must be executed in your database.

SQLiteDatabase db = criaBanco.getReadableDatabase();
Cursor cursor = db.rawQuery(sqlNome,null);
 if (cursor != null && cursor.moveToFirst()) {
                       cursor.moveToFirst();
                       String txt = cursor.getString(cursor.getColumnIndex(nomeColuna));

                   }

This should return you to String and then just use the textView.setText(txt);

The above code returns only the first result, your select seems to allow the return of all data, if you want to return multiple records, after the cursor.moveToFirst() do one of the while with the condition moveToNext()

do{

}while(cursor .moveToNext());
  • Thanks! In this case really only has one result. There is only the insertion of 1 data, the rest is only update.

1


getReadableDatabase() is a class method Sqliteopenhelper.

I suppose the class Criabanco inherited from it, so you can access that method and execute query, in this way:

Cursor cursor = criaBanco.getReadableDatabase().rawQuery(sqlNome, null);

Browser other questions tagged

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