views:

57

answers:

2

Hello, I want to create a ArrayAdapter for one spinner. So each element contain one string (which will be displayed in the spinner/list) and one value (e.g. an ID). How I can easily store a second value beside each string without implementing a new Adapter class?

Sincerely xZise

A: 

You could use a hashmap to map an ID to each string.

Tyler
But a hashmap doesn't implement SpinnerAdapter. So the spinner won't accept it. Sincerely xZise
xZise
A: 

You may create a class with two fields: one for text and another for ID. And implement toString method as returning the value of the text field. Here is an example:

package org.me.adaptertest;

import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends ListActivity {
    public static class Element {
        private String mText;
        private long mId;

        public Element(String text, long id) {
            mText = text;
            mId = id;
        }

        public long getId() {
            return mId;
        }

        public void setId(long id) {
            mId = id;
        }

        public String getmText() {
            return mText;
        }

        public void setmText(String mText) {
            this.mText = mText;
        }

        @Override
        public String toString() {
            return mText;
        }
    }

    private List<Element> mItems;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        mItems = new ArrayList<MainActivity.Element>();
        mItems.add(new Element("Element 1", 1));
        mItems.add(new Element("Element 2", 2));
        mItems.add(new Element("Element 3", 3));
        setListAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1,
                android.R.id.text1, mItems));
        getListView().setOnItemClickListener(new ListView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(MainActivity.this,
                        "ID is " + mItems.get(position).getId(),
                        Toast.LENGTH_SHORT).show();
            }
        });
    }
}
brambury
Ah I didn't noticed that the spinner don't need an ArrayAdapter<CharSequence>. Thanks ;)
xZise