database - 从 SQLite 数据库 Android 填充 Spinner

标签 database android sqlite spinner

我正在尝试创建一个将由 SQLite 表填充的动态下拉列表。我有一个 Cursor 对象,我可以从中提取我需要的数据。我已经能够使用以下代码将值加载到下拉列表中:

Spinner s = (Spinner) findViewById(R.id.spinner);
    ArrayAdapter adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    s.setAdapter(adapter);

    try{
        Cursor cursor = getAccounts();
        int accountnameIndex = cursor.getColumnIndexOrThrow(ACCOUNT_NAME);
        if(cursor.moveToFirst()){
            do{
                adapter.add(cursor.getString(accountnameIndex));
            } while(cursor.moveToNext());
        }
    } finally {
        MintLink.close();
    }

我的问题是我需要从下拉列表中选择一个选项来包含所选项目的 RowID。我需要能够选择一个项目并在后端访问该项目的值。例如,想想 HTML 中的下拉列表。每个下拉选择都有它自己的隐藏值。我需要为我隐藏此值,以便让我知道他们选择哪个 ID。

最佳答案

这是一个老问题,但是我在弄清楚这个问题时发现的第一个问题。这里有一个完整的源代码的详细解释,可能会减少一些跑腿工作。

答案确实是使用 SimpleCursorAdapter,它处理字符串列表,但也对匹配的 ID 字段进行特殊处理,该字段在选择行时返回。完成这项工作的关键是了解以下两个晦涩的信息:

1) 创建游标时,确保查询返回标题为“_id”的字段。此字段不需要显示在任何地方,但它的值将在选择列表项时传回。

2) 创建 SimpleCursorAdapter 时,您需要提供将放置行文本的 TextView 布局 ID。如果使用 android 提供的布局 android.R.layout.simple_spinner_item,您需要使用的文本 ID 是 android.R.id.text1。

主.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <Spinner
        android:id="@+id/spinner1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        ></Spinner>
</RelativeLayout>

Activity 代码:

public class TesterActivity extends Activity {
public Context mContext;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    // just for this example:
    // create database table with an id field and a text field and add some data
    class MyDBHelper extends SQLiteOpenHelper {
        public MyDBHelper(Context context) {
            super(context, "someDB", null, 2);
        }
        @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL("CREATE TABLE someTable (someIDF INTEGER, someTextF TEXT)");
        }
        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            db.execSQL("DROP TABLE IF EXISTS someTable");
            onCreate(db);
            db.execSQL("INSERT INTO someTable (someIDF, someTextF) VALUES (54, 'Some text')");
            db.execSQL("INSERT INTO someTable (someIDF, someTextF) VALUES (99, 'Some more text')");
            db.execSQL("INSERT INTO someTable (someIDF, someTextF) VALUES (173, 'Even more text')");
        }
    }
    SQLiteDatabase db = new MyDBHelper(this).getWritableDatabase();

    // get a cursor from the database with an "_id" field
    Cursor c = db.rawQuery("SELECT someIDF AS _id, someTextF FROM someTable", null);

    // make an adapter from the cursor
    String[] from = new String[] {"someTextF"};
    int[] to = new int[] {android.R.id.text1};
    SimpleCursorAdapter sca = new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, c, from, to);

    // set layout for activated adapter
    sca.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); 

    // get xml file spinner and set adapter 
    Spinner spin = (Spinner) this.findViewById(R.id.spinner1);
    spin.setAdapter(sca);

    // set spinner listener to display the selected item id
    mContext = this;
    spin.setOnItemSelectedListener(new OnItemSelectedListener() {
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id){
            Toast.makeText(mContext, "Selected ID=" + id, Toast.LENGTH_LONG).show();
        }
        public void onNothingSelected(AdapterView<?> parent) {}
        });
    }
}

关于database - 从 SQLite 数据库 Android 填充 Spinner,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2196426/

相关文章:

java - 范围为 (A..Z, 0..9) 和标点符号的随机字符生成器

php - 对于多服务器数据库系统,我们应该使用什么连接类型(mysql_connect、mysql_pconnect、PDO)?

database - 行锁会影响postgreSQL中的主从吗

mysql - SQL:根据另一个表中的列值选择列

Android Studio 任务compilefreeDebugKotlin 执行失败

java - Android SqLite : Select Rows Where Values Exists in Another Database Table

mysql - 存储 2 亿条记录的最节省空间的方法是什么?

android - 如何隐藏android微调器下拉列表中的第一项?

database - swift 和 SQLite

sql - sqlite 中简单字符串表的奇怪行为