我想从现有数据库中检索金额并将其显示在TextView中。
我已经创建了数据库。但是,当我尝试获取并显示金额时,我的应用会崩溃。
/ DataBaseHelper.java /
public Cursor getBalance(String amount) {
SQLiteDatabase db = this.getReadableDatabase();
String selectQuery = "SELECT * FROM " + TABLE_USER_BALANCE + " WHERE "
+ KEY_AMOUTNT + " = " + amount;
Log.e(LOG, selectQuery);
Cursor c = db.rawQuery(selectQuery, null);
if (c != null)
c.moveToFirst();
Balance b = new Balance();
b.setAmount(c.getInt(c.getColumnIndex(KEY_AMOUTNT)));
return (Cursor) b;
}
仪表板类:
public void saveCallBack(Balance balance) {
DataBaseHelper dataBaseHelper = new DataBaseHelper(context);
Cursor cursor = dataBaseHelper.getBalance(DashBoard.email);
while (cursor.moveToNext()) {
String s_amount = "";
s_amount =
cursor.getString(cursor.getColumnIndex(DataBaseHelper.KEY_AMOUTNT));
Double amount = 0.0;
if (AppUtility.isNum(s_amount)) {
amount = Double.parseDouble(s_amount);
}
TextView Amount = findViewById(R.id.amount);
Amount.setText(String.valueOf(amount));
}
}
答案 0 :(得分:2)
您无法将Balance
投射到Cursor
,因此您的应用程序将崩溃。您要么返回数据库Cursor
本身,要么返回Balance
对象。您已经制作了Balance
实例并在其中放置了一些值,所以我认为您的代码应为:
public Balance getBalance(String amount) {
...
Balance b = new Balance();
b.setAmount(c.getInt(c.getColumnIndex(KEY_AMOUTNT)));
return b;
}
我建议您学习有关Java转换的更多信息,以便您了解转换行为。