我有一个微调器,它是从db中检索到的Category
对象中填充的。分类表有_id
和category_name
列。我想在微调器中显示类别名称,但是当用户选择一个项目时,我需要它来检索所选项目的ID。我试过如下:如何检索动态微调器中所选项目的ID?
声明变量(类级):
int currCategoryId;
ArrayAdapter<String> adapter;
NotesManager manager = new NotesManager(this);
ArrayList<Category> arrListCategories;
ArrayList<String> arrListCategoriesString = new ArrayList<String>();
Spinner spCategories;
实例化他们onCreate
方法:
manager.getAllCategories();
arrListCategories = manager.getAllCategories();
for (int i = 0; i < arrListCategories.size(); i++)
{
Category currCategory = arrListCategories.get(i);
arrListCategoriesString.add(currCategory.getCategory_name().toString());
}
adapter=new ArrayAdapter<String> (this, android.R.layout.simple_spinner_item, arrListCategoriesString);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spCategories.setAdapter(adapter);
spCategories.setOnItemSelectedListener(spinnerListener);
这是我试过的spinnerListener:
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) {
}
};
但在这种情况下,应用程序崩溃,我得到一个“
串不能转换为类别”在这一行:
Category selectedCategory = (Category)spCategories.getItemAtPosition(pos);
我也试过这样:
currCategoryId = view.getId();
但后来不是1或2(取决于我选择什么类别,目前我有2个),我得到一个很长的数字...
我该如何解决它?我如何检索选定对象的ID?
尝试parent.getAdapter.getItem();并将此项目投到您想要的类,我希望这会工作 –
@AdeelPervaiz不,没有工作 - 没有getAdapter方法... – Igal