光标找不到列?

时间:2010-11-07 15:18:38

标签: android sqlite

我试图从表中加载一个值列表,但是光标找不到列? 错误的代码:

public final AccessToken[] fetchAccessTokenByServerId(final long serverId) {
    final Cursor c = db.query(
            ACCESS_TOKEN_TABLE,
            new String[] { ACCESS_TOKEN_COL_ID, ACCESS_TOKEN_COL_VALUE },
            ACCESS_TOKEN_COL_SERVER_ID + "=?",
            new String[] { Long.toString(serverId) },
            null,
            null,
            null);

    AccessToken[] result = new AccessToken[c.getCount()];
    for (int i = 0; i < result.length; i++) {
        long id = c.getLong(c.getColumnIndexOrThrow(ACCESS_TOKEN_COL_ID));
        String value = c.getString(c.getColumnIndexOrThrow(ACCESS_TOKEN_COL_VALUE));

        result[i] = new AccessToken(value, id, serverId);
        c.moveToNext();
    }
    return result;
}

public static final String COL_ID = "_id";
public static final String ACCESS_TOKEN_TABLE = "accesstoken";
public static final String ACCESS_TOKEN_COL_ID = COL_ID;
public static final String ACCESS_TOKEN_COL_SERVER_ID = "server_id";
public static final String ACCESS_TOKEN_COL_VALUE = "value";

但是for循环中的前两个语句失败了:

  

请求索引-1,大小为   1

该表存在以下列:_id(= int),server_id(= int)和value(= string)

有一个条目:1,1,测试

该功能的参数为1.

此致 xZise

2 个答案:

答案 0 :(得分:3)

在初始化光标后,执行以下操作:

c.moveToFirst();

答案 1 :(得分:2)

在这部分代码中我推荐这种方式

原件:

AccessToken[] result = new AccessToken[c.getCount()];
for (int i = 0; i < result.length; i++) {
    long id = c.getLong(c.getColumnIndexOrThrow(ACCESS_TOKEN_COL_ID));
    String value = c.getString(c.getColumnIndexOrThrow(ACCESS_TOKEN_COL_VALUE));

    result[i] = new AccessToken(value, id, serverId);
    c.moveToNext();
}

<强>修改:

if (c.moveToFirst()){
   int rowCount = c.getCount();
   AccessToken[] result = new AccessToken(rowCount);
   int recCount = 0;
   while (!c.isAfterLast()){
        long id = c.getLong(c.getColumnIndexOrThrow(ACCESS_TOKEN_COL_ID));
        String value = c.getString(c.getColumnIndexOrThrow(ACCESS_TOKEN_COL_VALUE));

        result[recCount++] = new AccessToken(value, id, serverId);
        c.moveToNext();
   }
   c.close(); // <-- IMPORTANT!!!!
}