我有一个微调器,其中填充了Category
从数据库中检索到的对象。Categories 表有_id
和category_name
列。我想在微调器中显示类别名称,但是当用户选择一个项目时,我需要它来检索所选项目的 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?