如果我只使用SQLite返回一行,是否需要循环? (Android Dev)

时间:2011-11-19 14:49:35

标签: java android

我一直在使用以下metod使用for循环,但我发现我只返回一行 - 所以有必要有一个循环吗?

,即我的代码类似于:

public String topSwimmerSponsor() {
    Cursor c = ourDatabase.rawQuery("SELECT " + KEY_SWIMMERLAPS + " * "
            + KEY_SPONSOR + " AS result, " + KEY_NAME + " FROM "
            + DATABASE_TABLE + " ORDER BY result DESC limit 1", null);

    String result = "";

    for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
        result = result + c.getString(1) + "\n";
    }
    return result;
}

但是我试图将其更改为以下内容:

public String topSwimmerSponsor() {
    Cursor c = ourDatabase.rawQuery("SELECT " + KEY_SWIMMERLAPS + " * "
            + KEY_SPONSOR + " AS result, " + KEY_NAME + " FROM "
            + DATABASE_TABLE + " ORDER BY result DESC limit 1", null);

    String result = "";

    result = result + c.getString(1) + "\n";

    return result;
}

然而我的应用程序崩溃了。实现这个的正确方法是什么?谢谢。

2 个答案:

答案 0 :(得分:3)

如果你只想要一个结果,你可以使用它:

if(c.moveToFirst())
  return c.getString(1) + "\n";

答案 1 :(得分:2)

您仍应移至第一个位置并检查您是否有一行:

if (c.moveToFirst()) {
    result = c.getString(1) + "\n";
}

此外,在循环中使用字符串连接是一个非常糟糕的主意,特别是在Android环境中,因为它创建了许多临时的StringBuilder和String对象,必须分配和垃圾收集。你应该使用StringBuilder:

StringBuilder builder = new StringBuilder();
for (...) {
    builder.append(...);
    builder.append(...);
}
String result = builder.toString();