Search code examples
androidandroid-listviewandroid-spinnerandroid-adaptersparse-array

How to use SparseArray as a source for Adapter?


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.


Solution

  • 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;
        }
    }