How to use SparseArray as a source for Adapter?
Asked Answered
I

1

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.

Igor answered 10/2, 2014 at 12:56 Comment(1)
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.Lidialidice
A
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;
    }
}
Axial answered 10/2, 2014 at 13:13 Comment(2)
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?Kyphosis
@Kyphosis yes, for example if you tag (e.g. pushing-pixels.org/2011/03/15/… 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 viewAxial

© 2022 - 2024 — McMap. All rights reserved.