从游标获取值



我有一个非常奇怪的问题。

当我想从光标中获取值时,我使用以下代码。

public Customers getCustomerByCursor(Cursor cursor){
Customers customer=new Customers();
cursor.moveToFirst();
customer.setID(cursor,getInt(cursor.getColumnIndex(CustomersDB.COLUMN_ID)));
customer.setAccount_name(cursor,getString(cursor.getColumnIndex(CustomersDB.COLUMN_ACCOUNTNAME)));
customer.setName(cursor.getString(cursor.getColumnIndex(CustomersDB.COLUMN_NAME)));
customer.setLastname(cursor,getString(cursor.getColumnIndex(CustomersDB.COLUMN_LASTNAME)));
customer.setAddress(cursor,getString(cursor.getColumnIndex(CustomersDB.COLUMN_ADDRESS)));
customer.setPhone(cursor,getString(cursor.getColumnIndex(CustomersDB.COLUMN_PHONE)));
customer.setIsactive(true); customer.setPassword(cursor,getString(cursor.getColumnIndex(CustomersDB.COLUMN_PASSWORD)));
return customer;
}

但是这些值没有正确输入到对象中或根本不输入。

例如,在下面的代码中,返回了 0,这是不正确的。

customer.setID(cursor,getInt(0)));

在其余行中不返回任何值。谁能帮忙?

customer.setID(cursor,getInt(cursor.getColumnIndex(CustomersDB.COLUMN_ID)));

应该很可能是customer.setID(cursor.getInt(cursor.getColumnIndex(CustomersDB.COLUMN_ID)));

getInt是游标对象的公共方法,因此要在游标上调用,您需要对游标对象的名称进行编码,后跟一个句号,然后是getInt方法,例如

cursor.getInt(column_offset_as_an_integer) // e.g. cursor.getColumnIndex(column_name_as_a_string) will return the column offset as an integer (if found)

您也不应假定 Cursor 方法moveToFirst总是移动到第一行,就像没有行一样,它不能移动到第一行。您应该始终检查返回值,一个布尔值,如果可以移动,它将为真,如果不能,则为假。

因此,您的代码似乎是:-

public Customers getCustomerByCursor(Cursor cursor){
Customers customer=new Customers();
if (cursor.moveToFirst()) {
customer.setID(cursor.getInt(cursor.getColumnIndex(CustomersDB.COLUMN_ID)));
customer.setAccount_name(cursor.getString(cursor.getColumnIndex(CustomersDB.COLUMN_ACCOUNTNAME)));
customer.setName(cursor.getString(cursor.getColumnIndex(CustomersDB.COLUMN_NAME)));
customer.setLastname(cursor.getString(cursor.getColumnIndex(CustomersDB.COLUMN_LASTNAME)));
customer.setAddress(cursor.getString(cursor.getColumnIndex(CustomersDB.COLUMN_ADDRESS)));
customer.setPhone(cursor.getString(cursor.getColumnIndex(CustomersDB.COLUMN_PHONE)));
customer.setIsactive(true);
customer.setPassword(cursor.getString(cursor.getColumnIndex(CustomersDB.COLUMN_PASSWORD)));
}
return customer;
}
  • 请注意,在游标不包含行的情况下,返回的 Customers 对象将不会设置任何值。您可能会检查返回的客户对象以检查是否出现此类情况。

最新更新