It happens that I have one Spinner
that has 4 names:
<string-array name="Nombres">
<item>Seleccione</item>
<item>Juan</item>
<item>Pedro</item>
<item>Carlos</item>
<item>Jose</item>
</string-array>
I want to save them in a MySQL database, but the field to save is of type int
, since it is my foreign key to relate that table to another. In HTML I usually do it like this:
<select class="nombre" name="nombre">
<option>Seleccione</option>
<option value="1">Juan</option>
<option value="2">Pedro</option>
<option value="3">Carlos</option>
<option value="3">Jose</option>
</select>
My question is can this be done on Android?:
<string-array name="Nombres">
<item>Seleccione</item>
<item value="1">Juan</item>
<item value="2">Pedro</item>
<item value="3">Carlos</item>
<item value="4">Jose</item>
</string-array>
I haven't found a similar example, that's why I'm asking.
Right now, I'm doing it like this:
Spinner spinner_nombres = (Spinner)findViewById(R.id.sp_nombre);
ArrayAdapter adapter_d = ArrayAdapter.createFromResource(this, R.array.Nombres, R.layout.spiner_item);
spinner_nombres.setAdapter(adapter_d);
String selec = spinner_nombres.getSelectedItem().toString();
int id_nombre = 0;
if (selec.equals("Juan")) {
id_nombre = 1;
} else
if (selec.equals("Pedro")) {
id_nombre = 2;
}
else
if (selec.equals("Carlos")) {
id_nombre = 3;
}
else
if (selec.equals("Jose")) {
id_nombre = 4;
}
And so I send it to PHP:
nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("idnombre",Integer.toString(id_nombre).trim()));
The detail is that I am using 14 Spinners
in my application and so much code is starting to drive me crazy, so I would really appreciate it if someone could help me.
If you are going to load the data into the Adapter in this way, it is not possible.
The option would be to create two
string-array
insidestyles.xml
, one for the names :and another for the values:
In the Adapter you load the names.
to obtain the value of some name you do it through the position:
You could use the values of
string-array
the containing the attributes that contain the values, but you would have to implement your own parser .It is actually much easier and better performing to do option two
string-array
.There is no easy way to do it in an XML file. As an alternative, you can use a
List<Pair<Integer, String>>
filling it by code.The documentation for
Pair
it is here: https://developer.android.com/reference/android/util/Pair.html