从光标获取值

时间:2018-08-25 22:18:57

标签: java android sqlite cursor

我有一个很奇怪的问题。

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

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)));

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

1 个答案:

答案 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;
}
  • 请注意,在“游标”不包含任何行的情况下,返回的“客户”对象将不会设置任何值。您可能会检查返回的Customer对象以检查是否发生这种情况。