我有一个很奇怪的问题。
当我想从游标中获取值时,我使用以下代码。
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)));
在其余行中不返回任何值。谁能帮忙吗?
答案 0 :(得分:0)
customer.setID(cursor,getInt(cursor.getColumnIndex(CustomersDB.COLUMN_ID)));
很有可能是customer.setID(cursor.getInt(cursor.getColumnIndex(CustomersDB.COLUMN_ID)));
即getInt
是Cursor对象的公共方法,因此要在Cursor上调用,需要对光标对象的名称进行编码,后跟句号,然后是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
总是移到第一行,就好像没有行一样,它也不能移到第一行。您应该始终检查返回值(布尔值),如果可以进行移动,则该值为true,否则将为false。
因此,您的代码似乎应该是:-
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;
}