Key Value Pair Data for Spinner (Android)

I've been looking for samples on using a Key Value pair on a Spinner but I couldn't find any. Of-course after I spent hours coming up with my own solution I stumbled across an example! By then it was too late and I decided to stick with my solution. The other sample might be a simpler solution for simple structures like: id and country name. The link is at the bottom.

Since I found a number of queries with no answers floating around I decided to strip out any client related information and post this sample.

I ended up extending the BaseAdapter to use my Hashtable as the underlying data structure and implementing the SpinnerAdapter so that it could be attached as an adapter to the Spinner.

This my extended BaseAdapter. I have updated this class. Check here for the update!.

package com.company.product.client.android.gui.views;

import java.util.Enumeration;
import java.util.Hashtable;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.SpinnerAdapter;
import android.widget.TextView;

import com.company.product.client.connection.CameraSource;
import com.company.product.client.connection.Constants;

public class KeyValueAdapter
    extends BaseAdapter
    implements SpinnerAdapter
{

    private static String TAG = "KeyValueAdapter";

    private final Context _context;
    private final Hashtable<String, CameraSource> _data;
    private final String[] _keys;


    public KeyValueAdapter(Context context, int textViewResourceId, Hashtable<String, CameraSource> objects)
    {
        _context = context;
        _data = objects;

        //get positions
        int i = 0;
        _keys = new String[_data.size()];

        for (final Enumeration<String> e = _data.keys(); e.hasMoreElements();)
        {
            _keys[i++] = e.nextElement().toString();
        }
    }


    public int getCount()
    {
        return _data.size();
    }


    public int getPositionFromKey(String searchKey)
    {
        for (int i = 0; i < _keys.length; i++)
        {
            if (_keys[i].equals(searchKey))
                return i;
        }
        return -1;
    }


    public Object getItem(int position)
    {
        return _data.get(_keys[position]);
    }


    public long getItemId(int position)
    {
        /*
        * I happened to be using long keys so I modified this function. you can leave it at:
        *  return position;
        */
        if (position >= _keys.length || position < 0)
        {
            return -1;
        }

        return _data.get(_keys[position]).getCameraKey();
    }


    public View getView(int position, View view, ViewGroup parent)
    {
        //Set the text of the view to what you want it to display.
        final int id = (_data.get(_keys[position])).getCameraNameId();

        final TextView text = new TextView(_context);
        text.setTextColor(Color.BLACK);
        text.setText(Constants.CAMERA_NAME_LOOKUP_TABLE[id]);

        return text;
    }

}


Here is the Activity

public class LiveViewActivity
    implements OnItemSelectedListener
{

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        try
        {

            setContentView(R.layout.live_view);
            _cameraSpinner = (Spinner) findViewById(R.id.spinCamera);
            _cameraSpinner.setOnItemSelectedListener(this);
            
            //My data in in a hashtable that I get from a method getData().. Implement your own..
            final Hashtable<String, CameraSource> cameraList = getData();

            final KeyValueAdapter adapter = new KeyValueAdapter(this, android.R.layout.simple_spinner_item, cameraList);
            _cameraSpinner.setAdapter(adapter);
        }
        catch (final Exception e)
        {
            Log.e(TAG, "onCreate() Exception: " + e.toString());
        }

    }
    
    public void onItemSelected(AdapterView<?> parent, View view, int position, long camKey)
    {
        try
        {
            //camKey is the long returned from getItemId()
            if (camKey < 0)
            {
                Log.w(TAG, "onItemSelected() camera Key is invalid");
                return;
            }

            //get object for the position
            final CameraSource camSrc = (CameraSource) _cameraSpinner.getAdapter().getItem(position);

            if (camSrc == null)
            {
                Log.w(TAG, "onItemSelected() camera source is null");
                return;
            }

            // ... do stuff .. //

        }
        catch (final Exception e)
        {
            Log.e(TAG, "onItemSelected() Exception: " + e.toString());
        }
    }
    
}

Here is the Layout Sinppet
 <Spinner
  android:id="@+id/spinCamera"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:drawSelectorOnTop="false"/>



Resources

0 comments: