我一直在使用以下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;
}
然而我的应用程序崩溃了。实现这个的正确方法是什么?谢谢。
答案 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();