Nima.S-H Nima.S-H - 5 months ago 55
Android Question

Set Key and Value in spinner

I have a spiner and I want set a key and a value on this,I use of HashMap,It's work,but show one row,like this:

enter image description here

Code:

final View rootView = inflater.inflate(R.layout.fragment_photos, container, false);

Spinner spin=(Spinner)rootView.findViewById(R.id.spinner1);

HashMap<Integer, String> P_Hash=new HashMap<Integer, String>();

Update Get_Information=new Update(rootView.getContext());

ArrayList<String> Province_NAME=new ArrayList<String>();
Province_NAME=Get_Information.GET_Province();

ArrayList<Integer> Province_ID=new ArrayList<Integer>();
Province_ID=Get_Information.Get_Province_ID();

for (int i = 0; i < Province_ID.size(); i++)
{
P_Hash.put(Province_ID.get(i), Province_NAME.get(i));
Log.d("Province_ID.get(i)", Province_ID.get(i)+"");
Log.d(" Province_NAME.get(i)", Province_NAME.get(i)+"");
}


ArrayAdapter<HashMap<Integer, String>> adapter = new ArrayAdapter<HashMap<Integer,String>>(rootView.getContext(), android.R.layout.simple_spinner_item);
adapter.add(P_Hash);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

spin.setAdapter(adapter);

Answer

Try this way,hope this will help you to solve your problem.

Prepare value for spinner

String[] spinnerArray = new String[Province_ID.size()];
HashMap<String,String> spinnerMap = new HashMap<String, String>();
for (int i = 0; i < Province_ID.size(); i++)
{
   spinnerMap.put(Province_NAME.get(i),Province_ID.get(i));
   spinnerArray[i] = Province_NAME.get(i);
}

Set value to spinner

ArrayAdapter<String> adapter =new ArrayAdapter<String>(context,android.R.layout.simple_spinner_item, spinnerArray);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);

Get value to spinner

String name = spinner.getSelectedItem().toString();
String id = spinnerMap.get(name);
Comments