How to set and get the id for the items in the spi

2019-09-04 07:42发布

问题:

I have a problem like I had a Spinner containing the Names of all developers working in the Company.
I have used the ArrayAdapter with a Array having the names of all the developers which is fetched from the database.

The problem is that when I update the Name Of Developer field, I get Only the Name of the Developer which is not enough to update the data as their can be multiple developers with the same name in the Company.
So now I require the id of the developers to update it..
How to store that id of the developers with the Spinner so that I can achieve this.

For example, I want to do like is as that we do in HTML::
<select>
<option id="1">Developer1</option>
<option id="2">Developer2</option>
<option id="3">Developer2</option>
<option id="4">Developer2</option>
</select>

where the id attached would be the database id.
I want to imitate this in android.

This the code that I have used to store the names in the array::

String alldevelopers = null;
try 
{
  ArrayList<NameValuePair> postP = new ArrayList<NameValuePair>();
  alldevelopers = CustomHttpClient.executeHttpPost("/fetchdevelopers.php", postP);
  String respcl = alldevelopers.toString();
  alldevelopersParser dev = new alldevelopersParser();
  ow = dev.parseByDOM(respcl);
} 
catch (Exception e) {
   e.printStackTrace();
}  

String developers[] = new String[ow.length];    //dev is a class object  
for (int n = 0; n < ow.length; n++)   
{  
  developers[n] = ow.developer[n][2];
}  

This is the Spinner that would spin the array..

final Spinner devl = (Spinner) findViewById(R.id.towner);  
devl.setOnItemSelectedListener(managetasks.this);
ArrayAdapter<String> b =   
new ArrayAdapter<String>getApplicationContext(),  
android.R.layout.simple_spinner_item,developers);  
b.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);  
devl.setAdapter(b);

回答1:

When you perform setOnItemSelectedListener on the spinner then you have method such as

public void onItemSelected(AdapterView<?> adapterView, View view,
                    int position, long id) {}

here you can findout the position of selected developer name of spinner and use this position to fetch data from array.