我正在努力从SQLite中获得一席之地。
这是我的DatabaseHelper片段:
public Expense getExpense(long id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(EXPENSE_TABLE_NAME,
new String[]{EXPENSE_COLUMN_ID, EXPENSE_COLUMN_TYPE, EXPENSE_COLUMN_PERSON_IN_DEBT, EXPENSE_COLUMN_AMOUNT,
EXPENSE_COLUMN_DESCRIPTION, EXPENSE_COLUMN_TIMESTAMP, EXPENSE_COLUMN_IS_PAID},
EXPENSE_COLUMN_ID + "=?",
new String[]{String.valueOf(id)}, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
assert cursor != null;
Expense expense = new Expense(
cursor.getInt(cursor.getColumnIndex(EXPENSE_COLUMN_ID)),
ERROR HERE -> (ExpenseType)cursor.getString(cursor.getColumnIndex(EXPENSE_COLUMN_TYPE)),
ERROR HERE -> (Person)cursor.getString(cursor.getColumnIndex(EXPENSE_COLUMN_PERSON_IN_DEBT)),
cursor.getDouble(cursor.getColumnIndex(EXPENSE_COLUMN_AMOUNT)),
cursor.getString(cursor.getColumnIndex(EXPENSE_COLUMN_DESCRIPTION)),
cursor.getString(cursor.getColumnIndex(EXPENSE_COLUMN_TIMESTAMP)),
cursor.getInt(cursor.getColumnIndex(EXPENSE_COLUMN_IS_PAID))); // true for 1
cursor.close();
db.close();
return expense;
}
Expense模型中的构造函数如下所示:
public Expense(int id, ExpenseType expenseType, Person person, Double amount, String description, String timestamp, int isPaid).
我在上面标记为错误的行上遇到了强制转换错误
“不可转换类型;无法将'java.lang.String'强制转换为'
com ... model.ExpenseType“
我该如何进行这项工作?在数据库中,对象
expenseType
和person
作为字符串添加。 最佳答案
这些行:
(ExpenseType)cursor.getString(cursor.getColumnIndex(EXPENSE_COLUMN_TYPE)),
(Person)cursor.getString(cursor.getColumnIndex(EXPENSE_COLUMN_PERSON_IN_DEBT))
您尝试将2个字符串强制转换为
ExpenseType
类型的对象和Person
类型的对象,但无法完成。您没有发布类
ExpenseType
和Person
,所以我不知道它们的构造函数,但是如果它们的构造函数将字符串作为参数,也许您可以这样做:new ExpenseType(cursor.getString(cursor.getColumnIndex(EXPENSE_COLUMN_TYPE))),
new Person(cursor.getString(cursor.getColumnIndex(EXPENSE_COLUMN_PERSON_IN_DEBT)))