Sunday, May 20, 2012

Blog

Custom Objects and Android Spinners

Oct 28

Written by:
10/28/2011 8:47 PM  RssIcon

Recently, I ran into an issue with SermonTrackr for Android that took me more than a few minutes to figure out. My task was to set the selection of the Spinner control to the ServiceType specified on the Service. I have a Spinner control that contains a list of ServiceType entities (inheriting BaseEntity). The signature of the BaseEntity and ServiceType are below:

   1: @SuppressWarnings("serial")
   2: public abstract class BaseEntity implements Serializable {
   3:     public int id;
   4: }
   5:  
   6: public class ServiceType extends BaseEntity {
   7:     public String serviceTypeName;
   8: }

When the ServiceActivity loads, I needed to set the selected ServiceType on the Spinner. I had the id of the ServiceType, but that does not necessarily match the index of the items as they appear on the Spinner. In order to get the position of the selected item in the Spinner, I iterated through the items in the ServiceTypeListAdapter, and checked the id until I found a match of the serviceTypeId. Because the Spinner is bound to the adapter, the index is easily determined. It just took me a while to figure that out. The full method that I use is shown below.

   1: private int getServiceTypeSpinnerPosition(int serviceTypeId) {
   2:         int position = -1;
   3:         int serviceTypesCount = serviceTypesAdapter.getCount();
   4:         
   5:         for (int i=0; i<serviceTypesCount; i++) {
   6:             int curServiceTypeId = serviceTypesAdapter.getItem(i).id;
   7:             if (serviceTypeId == curServiceTypeId) {
   8:                 position = serviceTypesAdapter.getPosition(serviceTypesAdapter.getItem(i));
   9:                 break;
  10:             }
  11:         }
  12:         
  13:         return position;
  14:     }

Until next time, keep thinking outside the box.

JB

Tags:
Categories:

Your name:
Gravatar Preview
Your email:
(Optional) Email used only to show Gravatar.
Your website:
Title:
Comment:
Security Code
CAPTCHA image
Enter the code shown above in the box below
Add Comment   Cancel 

Blog

Custom Objects and Android Spinners

Blog

There are no recent comments on this blog.

Blog

Blog

Skip Navigation Links.

Blog

Copyright 2011 by Burris Consulting Group LLC