使用 android 在 SQLite 数据库 table 中使用 WHERE 子句检索值

Retrieving values using WHERE Clause in SQLite Database table using android

我正在尝试从名称与提供的字符串相匹配的距离列中获取值。请参阅下面的代码:

    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 的资产文件夹中使用外部数据库文件,并使用几乎相同的函数来填充我的微调器。 它与微调器一起工作正常,但在使用上述函数时返回空值。 这是我的 table :

帮我解决问题。 提前致谢。

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;
    //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;
    }

我执行的迭代有问题 工作代码如下:

    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;
}