1

So, I have an ArrayList that has name and id

Gil 232
Asty 2423 and so on. 

To use it in the spinner, what I did was to create two separate String Arraylists. One containing the names and the other the corresponding ids. So, that once the user is selected, I will get the corresponding id from the position.

I am not sure how to do that last part. As to, how to get the position?> parent.getItemAtPosition(pos).toString(); This gives me the name again and not the position of the name in the ArrayList which I can use to retrieve the ID from the other list. How to do it? And, is their a better way to go about it?

ngesh
  • 13,398
  • 4
  • 44
  • 60
Hick
  • 35,524
  • 46
  • 151
  • 243

2 Answers2

1
public class User {
    public int id;
    public String name;
}

public class CustomAdapter extends ArrayAdapter<Data> implements Spinner
                                                      .OnItemSelectedListener {
    @Override
    public View getView(int position, View convertView, ViewGroup parent){
        LayoutInflater inflater = getLayoutInflater();
        View view = inflater.inflate(android.R.layout.simple_spinner_item,
                        parent, false);
        Data data = getItem(position);
        // Do something with data and view here
        return view;
    }

    @Override
    public void onItemSelected(AdapterView<?> arg0, View arg1, 
                                                int position, long arg4) {
        Data data = getItem(position);
        // Do something with data here
    }

    @Override
    public void onNothingSelected(AdapterView<?> arg0) {
    }

}

Then create an ArrayList<Data> and use with your CustomAdapter.

ngesh
  • 13,398
  • 4
  • 44
  • 60
0

The pos variable is the position of item selected from Spinner, so you can use this position to get the id (from second ArrayList) of corresponding name which is selected.

As a alternative you can also create a HashMap<String,String> map and in that map put values like map.put(name,id); so when user will select value from Spinner you will have the name selected.And then use the map to get corresponding id

like String id = map.get(selected_name);

Hope it will help.

Arun Badole
  • 10,977
  • 19
  • 67
  • 96