5

I have a sparse array of values which I want to populate in a Spinner, and when the item is selected, I want to get the id (which is the key from the sparse array).

What is the preferred way of creating an adapter from a SparseArray?

Is it possible to subclass an existing Adapter like BaseAdapter or ListAdapter So that the items will have a key from the SparseArray as item id?

Not knowing how to achieve the above, I am thinking of creating a simple ArrayAdapter instance and giving it values from the SparseArray as a source and when the item is selected, to look up the key by the value, which I think won't be efficient.

Sergo Pasoevi
  • 2,833
  • 3
  • 27
  • 41
  • I believe the BaseAdapter is an abstract class and ListAdapter is extends it with a List to store the data. You can very well extend BaseAdapter. – midhunhk Feb 10 '14 at 13:01

1 Answers1

13

Creating a subclass of BaseAdapter should work fine. E.g. take

public abstract class SparseArrayAdapter<E> extends BaseAdapter {

    private SparseArray<E> mData;
    public void setData(SparseArray<E> data) {
        mData = data;
    }

    @Override
    public int getCount() {
        return mData.size();
    }

    @Override
    public E getItem(int position) {
        return mData.valueAt(position);
    }

    @Override
    public long getItemId(int position) {
        return mData.keyAt(position);
    }
}

and extend that one to get some actual functionality. For example like

public class SparseStringsAdapter extends SparseArrayAdapter<String> {
    private final LayoutInflater mInflater;
    public SparseStringsAdapter(Context context, SparseArray<String> data) {
        mInflater = LayoutInflater.from(context);
        setData(data);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        TextView result = (TextView) convertView;
        if (result == null) {
            result = (TextView) mInflater.inflate(android.R.layout.simple_list_item_1, null);
        }
        result.setText(getItem(position));
        return result;
    }
}
zapl
  • 63,179
  • 10
  • 123
  • 154
  • Since SparseArrays can have keys different than the index, is it possible to access the actual key of item in onlick when I get the adapterView? – Rachit Jan 09 '15 at 13:44
  • 1
    @Rachit yes, for example if you tag (e.g. http://www.pushing-pixels.org/2011/03/15/android-bits-and-pieces-view-tags.html talks about that a bit) the view in `getView` or by adding a method to your custom adapter so that you can get it based on the position of the view – zapl Jan 09 '15 at 17:02