我正在尝试从名称与提供的字符串匹配的距离列中获取值。参见下面的代码:
public String getDistance(String station_name){
String distance = null;
Cursor cursor = database.rawQuery("SELECT distance from station_data where name =? ", new String[] {station_name} );
cursor.moveToFirst();
while(cursor.moveToNext()){
distance = cursor.getString(0);
cursor.moveToNext();
}
cursor.close();
return distance;
}
我在android的Assets文件夹中使用了一个外部数据库文件,并使用了几乎相同的功能来填充我的微调框。 它与微调器一起正常工作,但使用上述函数时返回空值。 这是我的桌子:
帮我找出问题所在。 预先感谢。
答案 0 :(得分:0)
//Once try this. It will definitely work.
public String getDistance(String station_name){
String distance = null;
Cursor cursor = database.rawQuery("SELECT distance from station_data where name =? ", new String[] {station_name} );
if (cursor.moveToFirst())
{
distance = cursor.getString(0);
}
cursor.close();
return distance;
}
//有关代码中的错误,请参见此处。
// cursor.moveToFirst()将光标移动到光标的第一个索引。
// cursor.moveToNext()将光标移至下一个索引。
//看您在这里做什么。
public String getDistance(String station_name){
String distance = null;
Cursor cursor = database.rawQuery("SELECT distance from station_data where name =? ", new String[] {station_name} );
cursor.moveToFirst(); // CURSOR INDEX = 0
while(cursor.moveToNext()){ // CURSOR INDEX = 1
distance = cursor.getString(0);
cursor.moveToNext();
}
cursor.close();
return distance;
}
答案 1 :(得分:0)
我执行的迭代有问题 工作代码如下:
public String getDistance(String station_name){
String distance = null;
Cursor cursor = database.rawQuery("SELECT distance from station_data WHERE name =? ", new String[] {station_name} );
cursor.moveToFirst();
while(!cursor.isAfterLast()){
distance = cursor.getString(0);
cursor.moveToNext();
}
cursor.close();
return distance;
}
答案 2 :(得分:-1)
public String getDistance(String station_name){
String distance = null;
Cursor cursor = database.rawQuery("SELECT distance from station_data where name =? ",
new String[] {station_name} );
if(cursor.length() > 0){
cursor.moveToFirst();
distance = cursor.getString(0);
}
cursor.close();
return distance;