title: How to retrieve an ID of the selected item in a dynamic Spinner?
body: <p>I have a spinner which is populated with <code>Category</code> objects that are retrieved from the db. The Categories table has <code>_id</code> and <code>category_name</code> 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:</p>
  
  <p>Declaring variables (in class level):</p>
  
  <pre><code>int currCategoryId;
  
  ArrayAdapter&lt;String&gt; adapter;
  
  NotesManager manager = new NotesManager(this);
  ArrayList&lt;Category&gt; arrListCategories; 
  ArrayList&lt;String&gt; arrListCategoriesString = new ArrayList&lt;String&gt;();
  
  Spinner spCategories;
  </code></pre>
  
  <p>Instantiating them in <code>onCreate</code> method:</p>
  
  <pre><code>manager.getAllCategories();
      arrListCategories = manager.getAllCategories();
  
      for (int i = 0; i &lt; arrListCategories.size(); i++) 
      {
          Category currCategory = arrListCategories.get(i);
          arrListCategoriesString.add(currCategory.getCategory_name().toString());            
      }
  
      adapter=new ArrayAdapter&lt;String&gt; (this, android.R.layout.simple_spinner_item, arrListCategoriesString);
      adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
      spCategories.setAdapter(adapter);
      spCategories.setOnItemSelectedListener(spinnerListener);
  </code></pre>
  
  <p>And this is the spinnerListener I tried:</p>
  
  <pre><code>OnItemSelectedListener spinnerListener = new OnItemSelectedListener() 
      {       
          public void onItemSelected(AdapterView&lt;?&gt; 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&lt;?&gt; arg0) {    
  
          }                   
      };
  </code></pre>
  
  <p>But in this case the app crashes and I'm getting a "</p>
  
  <blockquote>
    <p>String cannot be cast to Category" at this line: <code>Category
    selectedCategory = (Category)spCategories.getItemAtPosition(pos);</code></p>
  </blockquote>
  
  <p>I also tried this:</p>
  
  <pre><code>currCategoryId = view.getId();
  </code></pre>
  
  <p>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...</p>
  
  <p>How can I fix it? How can I retrieve the ID of the selected object?</p>