如何从 Spinner 获取 id 并由数据库填充

How to get id from Spinner and it is populated by database

我通过使用本地数据库填充它来创建 Spinner。 在我的 DBHelper 中,我使用了 List<String>

public List<String> getServices(){
    List<String> labels = new ArrayList<String>();

    // Select All Query
    String selectQuery = "SELECT  * FROM " + TBL_SERVICES;

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

    // looping through all rows and adding to list
    if (cursor.moveToFirst()) {
        do {
            labels.add(cursor.getString(1));
        } while (cursor.moveToNext());
    }

    // closing connection
    cursor.close();
    db.close();

    // returning lables
    return labels;
}

在我的片段中,我使用它来加载我的微调器

private void loadSpinnerData() {

    initialazeDatabase();

    // Spinner Drop down elements
    List<String> lables = dbHelper.getServices();

    // Creating adapter for spinner
    ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_spinner_item, lables);
            .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    // attaching data adapter to spinner
    spn_services.setAdapter(dataAdapter);
}

之后我试图获取它的 ID,但我只从数据库中获取位置而不是 ID

spn_services.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        public void onItemSelected(AdapterView<?> parent, View view,
                                   int pos, long id) {
           Log.e(TAG, "My service id is " + pos + "My Id is "+ id);

        }

id 只是返回与 pos 相同的值。如何获取从数据库中保存的rowID?

**

我的服务中只有 2 列 table 它的 ID 和 services_name。

我调试了一下,看到了这个

它只获取我的字符串而不是数据库中的 rowID,因为我的数据库看起来像这样

您可以通过更改查询来获取 rowid:

String selectQuery = "SELECT rowid, * FROM " + TBL_SERVICES;

但是问题是你不能使用ArrayAdapter

ArrayAdapter总是 使用位置作为 id。由于您是从数据库中获取 id,因此适合您的正确解决方案是 CursorAdapter 的子类。在您的情况下,您可以使用 SimpleCursorAdapter.

所以让我们将您的 dbHelper getServices() 方法更改为 return a Cursor:

    public Cursor getServicesCursor() {

        // Select All Query
        String selectQuery = "SELECT rowid AS _id, * FROM " + TBL_SERVICES;

        SQLiteDatabase db = this.getReadableDatabase();
        return db.rawQuery(selectQuery, null);
    }

CursorAdapter 的文档说

The Cursor must include a column named "_id" or this class will not work.

所以我们在查询中将 "rowid" 重命名为“_id”。

那就简单了:

    private void loadSpinnerData() {

        initialazeDatabase();

        // Spinner Drop down cursor
        Cursor servicesCursor = dbHelper.getServicesCursor();

        // map the cursor column names to the TextView ids in the layout
        String[] from = { "services_name" };
        int[] to = { android.R.id.text1 };

        // Creating adapter for spinner
        SimpleCursorAdapter dataAdapter = new SimpleCursorAdapter(this, 
              android.R.layout.simple_spinner_dropdown_item,
              servicesCursor, from, to, 0);

        // attaching data adapter to spinner
        spn_services.setAdapter(dataAdapter);
    }