我有一个数据库助手类:
public Cursor getAllData() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("select * from " + TABLE_NAME, null);
return res;
}
当我想显示活动按钮中的所有数据时,它可以正常工作,即:
public void onbtnViewAllRecordsClick(View v) {
Cursor res = myDb.getAllData();
if(res.getCount() == 0) {
// Show message
showMessage("Error", "No data found");
return;
}
StringBuffer buffer = new StringBuffer();
while (res.moveToNext()) {
buffer.append("ID " + res.getString(0) + "\n");
buffer.append("Amount " + res.getString(1) + "\n");
buffer.append("Cost " + res.getString(2) + "\n");
buffer.append("Date " + res.getString(3) + "\n\n");
}
// Show all data
showMessage("Data",buffer.toString());
}
我现在正试图弄清楚如何在加载应用程序时从数据库中获取某些细节并将其显示在默认活动上。我在默认活动上有一个EditText,想要在数据库中添加所有'Amount'值,并在EditText中显示它。
有人能指出我的写作方向。
答案 0 :(得分:1)
假设您要添加的所有值都是整数,那么您可以执行此操作。
onCreate
方法现在,当您有数据检索要添加的特定值并显示它们在编辑文本中将它们相加时,如下例所示
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_default);
...
...
displayValues();
...
...
}
private void displayValues(){
Cursor res = myDb.getAllData();
if(res.getCount() == 0) {
// Show message
showMessage("Error", "No data found");
return;
}
StringBuffer buffer = new StringBuffer();
int total = 0;
// assuming here that you only have to add the Amount values
while (res.moveToNext()) {
//hear you can initilize variables or arrays with the other values from your db which you want to use further.
total +=res.getInt(1);//addind up all the values of Amount column
}
yourEditText.setText(""+total);
}