我正在构建一个 Android 应用程序,并设置了一个基本 DBObject 类来简化表交互。DBObject 构造函数设置一个游标并将其传递给虚拟方法 loadRecord,子类将覆盖该方法以加载其自己的属性。根据 loadRecord 末尾的 Log.i 调用,属性都是正确的,但是一旦调用方法取回对象,所有数据成员都具有类声明中定义的默认值,而不是加载的值(字符串为 null ,浮点数为 0.00 等)。
public abstract class DBObject {
....
public DBObject(DBHelper dbh, String table_name, int _id){
// loads an existing DBObject from the database by id
this.dbh = dbh;
this.TABLE_NAME = table_name;
this.id = _id;
setupDbr();
String sql = String.format("select * from %s where _id=%d", TABLE_NAME, id);
Cursor cur = dbr.rawQuery(sql, null);
if (cur.getCount() == 0){
throw new RowDoesNotExistException(id);
} else if (cur.getCount() > 1){
throw new RowDoesNotExistException("Record is not unique.", id);
}
cur.moveToFirst();
loadRecord(cur);
}
....
abstract void loadRecord(Cursor cur);
此构造函数调用重写的 loadRecord,它在子类中如下所示:
public class Expense extends DBObject{
public String date = null;
public String supplier = null;
public String description = null;
public float amount = 0.00f;
public boolean receipt = false;
public Expense(DBHelper dbh, String _id){
super(dbh, DBHelper.EXPENSE_TABLE, _id);
...
@Override
void loadRecord(Cursor cur){
id = cur.getInt(0);
date = cur.getString(1);
supplier = cur.getString(2);
description = cur.getString(3);
amount = cur.getFloat(4);
receipt = (cur.getInt(5) == 1);
Log.i("net.bradmont.reimburseit", String.format("%d, %s, %s, %s", id, date, supplier, description));
}
在 DBObject 构造函数中设置的成员保持原样。我对此完全不知所措......
提前致谢!