Android 如何在动态微调器中检索选定项的ID?
我有一个微调器,其中填充了从数据库检索的Android 如何在动态微调器中检索选定项的ID?,android,sqlite,object,spinner,Android,Sqlite,Object,Spinner,我有一个微调器,其中填充了从数据库检索的类别对象。类别表有\u id和category\u name列。我想在微调器中显示类别名称,但当用户选择项目时,我需要它来检索所选项目的ID。我尝试了以下操作: 声明变量(在类级别): 这是我试过的喷丝板监听器: OnItemSelectedListener spinnerListener = new OnItemSelectedListener() { public void onItemSelected(Adap
类别
对象。类别表有\u id
和category\u name
列。我想在微调器中显示类别名称,但当用户选择项目时,我需要它来检索所选项目的ID。我尝试了以下操作:
声明变量(在类级别):
这是我试过的喷丝板监听器:
OnItemSelectedListener spinnerListener = new OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
// An item was selected.
//currCategory = (String) parent.getItemAtPosition(pos).toString();
//selectedCategory =
Category selectedCategory = (Category)spCategories.getItemAtPosition(pos);
currCategoryId = selectedCategory.getId();
}
public void onNothingSelected(AdapterView<?> arg0) {
}
};
但是我得到的不是1或2(取决于我选择的类别,目前我有2个),而是一个很长的数字
我怎样才能修好它?如何检索所选对象的ID?无论如何都不能使用
ArrayAdapter
,因为它仅用于字符串(而不是类别)。因此,你得到了一个铸造例外。由于类别ArrayList
和字符串ArrayList
(用于ArrayAdapter
)的顺序相同,因此只需使用
Category selectedCategory = arrListCategories.get(pos);
在您的
onItemSelected()
方法中,我将使用SimpleCorsOrAdapter
,因为它存储多个列,而不是只存储一个列的ArrayAdapter
首先更改NotesManager.getAllCategories()
以返回使用以下内容的光标
:
"SELECT _id, category_name FROM Table;"
如果需要,可以按字母顺序排列结果:
"SELECT _id, category_name FROM Table ORDER BY category_name;"
下一步将此光标直接绑定到微调器:
Cursor cursor = manager.getAllCategories();
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, cursor, new String[] {"category_name"}, new int[] {android.R.id.text1});
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spCategories.setAdapter(adapter);
最后在您的OnItemSelectedListener
中,一切都准备就绪并等待:
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
// The parameter id already refers to your Category table's id column,
}
public void已选择(AdapterView父视图、视图视图、整数位置、长id){
//参数id已引用类别表的id列,
}
无需额外的get()
调用或将游标转换为列表 尝试parent.getAdapter.getItem();并把这个项目投给你想要的班级,我希望这会work@AdeelPervaiz不,不起作用-没有getAdapter方法…是的,它起作用了!我尝试使用这一行:Category selectedCategory=(Category)parent.getItemAtPosition(pos)代码>,但显然这不起作用。我现在明白我的错误了。非常感谢你!
"SELECT _id, category_name FROM Table ORDER BY category_name;"
Cursor cursor = manager.getAllCategories();
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, cursor, new String[] {"category_name"}, new int[] {android.R.id.text1});
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spCategories.setAdapter(adapter);
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
// The parameter id already refers to your Category table's id column,
}