Igal Igal - 2 months ago 9
Android Question

How to retrieve an ID of the selected item in a dynamic Spinner?

I have a spinner which is populated with Category objects that are retrieved from the db. The Categories table has _id and category_name columns. I want to show the category name in the spinner, but when the user selects an item, I need it to retrieve the selected item's ID. I tried the following:

Declaring variables (in class level):

int currCategoryId;

ArrayAdapter<String> adapter;

NotesManager manager = new NotesManager(this);
ArrayList<Category> arrListCategories;
ArrayList<String> arrListCategoriesString = new ArrayList<String>();

Spinner spCategories;


Instantiating them in onCreate method:

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);


And this is the spinnerListener I tried:

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) {

}
};


But in this case the app crashes and I'm getting a "String cannot be cast to Category" at this line:
Category selectedCategory = (Category)spCategories.getItemAtPosition(pos);


I also tried this:

currCategoryId = view.getId();


But then instead of 1 or 2 (depending on what category I selected, currently I have 2 of them), I'm getting a very long number...

How can I fix it? How can I retrieve the ID of the selected object?

Answer

You can't use the ArrayAdapter anyway because it's for Strings only (not Categories). Hence why you're getting a casting exception. Since you have your Category ArrayList and your String ArrayList (which is used for the ArrayAdapter) in the same order, just use

Category selectedCategory = arrListCategories.get(pos);

in your onItemSelected() method