CursorIndexOutOfBoundsException android

时间:2014-01-22 12:23:42

标签: android

在我的代码中,当cursor为null时,我会遇到CursorIndexOutOfBoundsException Index 0 requested, with a size of 0 in Android

的异常

我该如何解决这个问题?

public Cursor getCustAccount(long custRef){
    openReadable();
    Cursor cursor;
    cursor = database.rawQuery(" SELECT CustAccountId AS _id,AccountNo as AccountNo,BankName as BankName,BranchName as BranchName FROM tblCustAccount  WHERE CustRef =" + custRef , null);

    if (cursor != null)
        cursor.moveToFirst();

    return cursor;
}

public ArrayList<String> getCustAccountString(long custRef) {
    Cursor cursor = getCustAccount(custRef);

    ArrayList<String> listAccount = new ArrayList<String>();

    do {
        listAccount.add(String.valueOf(cursor.getInt(1)));

    } while(cursor.moveToNext());

    return listAccount;
}

3 个答案:

答案 0 :(得分:1)

光标中没有数据。在任何moveToFirst()来电之前,您应该检查get...()是否成功:

if (cursor.moveToFirst()) {
  do {
    listAccount.add(String.valueOf(cursor.getInt(1)));
  } while(cursor.moveToNext());
}

答案 1 :(得分:0)

使用: -

if(cursor != null && cursor.moveToFirst()){
    return cursor;
    }
    return null;

public abstract boolean moveToFirst ()

将光标移动到第一行。

如果光标为空,此方法将返回false。

返回 此举是否成功。

答案 2 :(得分:0)

尝试以下代码:

if (cursor.getCount() > 0) {
     do {
        listAccount.add(String.valueOf(cursor.getInt(1)));

    } while(cursor.moveToNext());
 }