MoLab
MoLab

Reputation: 17

Display data from database into text view (Android)

This is my code for database class (DatabaseHelper.java)

public Cursor getAllData(){
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor res = db.rawQuery("select * from "+TABLE_NAME,null);
        return res;
    }

This is another class which is (MainSuggestion.java)

public class MenuSuggestion extends AppCompatActivity {
    DatabaseHelper myDb;
    @Override 
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_menu_suggestion);
<br/>
        Cursor res = myDb.getAllData();
        if (res.moveToFirst()) {             
            TextView bmi = (TextView) findViewById(R.id.textView9);
            TextView kcal = (TextView) findViewById(R.id.textView10);
            bmi.setText(res.getString(3));
            kcal.setText(res.getString(4));
        }
    }
}

Can someone tell me, what's wrong with my code?

Upvotes: 0

Views: 169

Answers (2)

JoeyJubb
JoeyJubb

Reputation: 2321

The exact reason this isn't working is because "myDb" is null on this line.

 Cursor res = myDb.getAllData();

However, I recommend you Running a Query with a CursorLoader. It might seem overkill, loading stuff from the database on the main thread like you are can lead to ANR errors.

Upvotes: 4

Lay Leangsros
Lay Leangsros

Reputation: 9296

Query data from database, you have to use:

this.getReadableDatabase();

You use getWritableDatabase() when you want to write, update, delete data into/from database.

Upvotes: 0

Related Questions