[英]Display data from database into text view (Android)
This is my code for database class (DatabaseHelper.java) 这是我的数据库类代码(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) 这是另一个类(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? 有人可以告诉我,我的代码有什么问题吗?
The exact reason this isn't working is because "myDb" is null on this line. 不起作用的确切原因是因为“ myDb”在此行中为空。
Cursor res = myDb.getAllData();
However, I recommend you Running a Query with a CursorLoader . 但是,我建议您使用CursorLoader运行查询 。 It might seem overkill, loading stuff from the database on the main thread like you are can lead to ANR errors. 从主线程上的数据库中加载内容可能会导致ANR错误,这似乎有些矫kill过正。
Query data from database, you have to use: 从数据库查询数据,您必须使用:
this.getReadableDatabase();
You use getWritableDatabase()
when you want to write, update, delete data into/from database. 要在数据库中写入,更新数据或从中删除数据时,可以使用getWritableDatabase()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.