【问题标题】:How can I implement a String variable instead of 'Landschaft'?如何实现字符串变量而不是“Landschaft”?
【发布时间】:2015-03-07 17:44:53
【问题描述】:

我创建了一个SpinnerActivity,如下所示:

http://img4.fotos-hochladen.net/uploads/bildschirmfotovse8j4po1t.png

现在,例如,如果我选择“Landschaft”(英文:landscape),我想在 DatabaseHandler.java 中搜索属于“Landschaft”(风景)类别的位置

因此我在DatabaseHandler.java中写了如下方法:

在这个方法中,我刚刚写了Categorie = Landscape。

但是,我希望将 Spinner 中选定的 SpinnerArray(Landschaft、Brücken 等)插入到我的 DatabaseHandler 而不是“Landschaft”中,我该怎么做?

public List<Position> getAllPositionsWithCategory() {
        List<Position> positionList = new ArrayList<Position>();

        String selectQuery = "SELECT * FROM " + TABLE_POSITIONS
                + " WHERE Kategorie = 'Landschaft'";

        SQLiteDatabase db = this.getWritableDatabase();

        Cursor cursor = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list

        if (cursor.moveToFirst()) {

            do {

                Position position = new Position();

                position.setID(Integer.parseInt(cursor.getString(0)));

                position.setName(cursor.getString(1));

                position.setKategorie(cursor.getString(2));

                position.setLaenge(cursor.getFloat(3));

                position.setBreite(cursor.getFloat(4));

                // Adding position to list

                positionList.add(position);

            } while (cursor.moveToNext());

        }
}

【问题讨论】:

    标签: java android database sqlite android-sqlite


    【解决方案1】:

    只需将查询中的固定字符串替换为?,并将要插入的值传递到db.rawQuery() 的第二个参数中。

    以下可能适用于您的情况:

    String selectQuery = "SELECT * FROM " + TABLE_POSITIONS
                + " WHERE Kategorie = ?";
    // ...
    Cursor cursor = db.rawQuery(selectQuery, new String[] { "Landschaft" });
    

    您现在可以用您选择的变量替换您的字符串 "Landschaft"

    另请参阅:http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html#rawQuery(java.lang.String,%20java.lang.String[])

    【讨论】:

      猜你喜欢
      • 2020-08-05
      • 2021-02-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-11
      • 2020-03-19
      • 1970-01-01
      • 2020-01-02
      相关资源
      最近更新 更多