如何从sqlite获取数据 - Android

时间:2011-09-20 14:06:16

标签: android sqlite

我在android中的sqlite数据库中获取元素有点问题。我的数据库看起来像这样:

id  /   serverName  /  objectId  /  objectOid  /  ....//objectId is actually userId-which I need to compare

我正在从服务器接收数据,我需要从服务器检查用户的ID和数据库中的本地用户ID。我有这段代码:

public static Integer lUserIdByServerUserId(int serverUserId, String serverName){
    return localUserIdByServerUserId( serverUserId,  serverName);

}

private static Integer localUserIdByServerUserId(int serverUserId, String serverName){
    DataBaseHelper dbHelper = new DataBaseHelper(context, "ops_sys_tpl.sqlite",null,1);
    String query = "SELECT id FROM users WHERE objectId = "+serverUserId+" AND serverName = '"+serverName+"' LIMIT 1";
    ArrayList<String> result = new ArrayList<String>();
    cursor = dbHelper.executeSQLQuery(query);
    cursor.moveToFirst();
    while(!cursor.isAfterLast()) {
        result.add(cursor.getString(cursor.getColumnIndex("objectId")));
        cursor.moveToNext();
    }

    Log.i("result ","Result : "+result.toString());
    Log.i("CURSOR ","Cursor Position : "+cursor.getPosition());
    Integer uuid = Integer.parseInt(result.get(cursor.getColumnIndex("objectId")));
    Log.w("localUSerByIdServerUserId","LocalUserByIdServerUserId result : "+uuid);
    cursor.close();
    return uuid;
}

我正在尝试检查数据库中的所有条目,如果有匹配则返回它。我正在调用这样的方法:

            uuId = rpc.lUserIdByServerUserId(userId,newServerName);

我在这一行得到了这个例外:Integer uuid = Integer.parseInt(result.get(cursor.getColumnIndex("objectId")));

  09-20 16:55:47.647: WARN/System.err(31031): java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
09-20 16:55:47.647: WARN/System.err(31031):     at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:257)
09-20 16:55:47.647: WARN/System.err(31031):     at java.util.ArrayList.get(ArrayList.java:311)
09-20 16:55:47.647: WARN/System.err(31031):     at com.stampii.stampii.comm.rpc.RPCCommunicator.localUserIdByServerUserId(RPCCommunicator.java:1083)
09-20 16:55:47.647: WARN/System.err(31031):     at com.stampii.stampii.comm.rpc.RPCCommunicator.lUserIdByServerUserId(RPCCommunicator.java:1066)
09-20 16:55:47.657: WARN/System.err(31031):     at com.stampii.stampii.comm.rpc.InfoStartRPCPacket.executeBefore(InfoStartRPCPacket.java:176)
09-20 16:55:47.657: WARN/System.err(31031):     at com.stampii.stampii.user.UserLogin$2$1.run(UserLogin.java:212)
09-20 16:55:47.657: WARN/System.err(31031):     at java.lang.Thread.run(Thread.java:1102)
09-20 16:55:47.657: WARN/ERROR(31031):  Error  - java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0

实际上我的数据库中只有一个测试条目与从服务器返回的userID相同。

任何想法都是我的错误以及如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

问题是由于光标的位置

尝试使用此代码将光标定位到起点。

 if (mNotesCursor.moveToFirst()) {
      do {
         result.add(cursor.getString(cursor.getColumnIndex("objectId")));
      } while (mNotesCursor.moveToNext());
 }