Siddharth Siddharth - 1 year ago 108
Android Question

How to send value to server based on user clicked in spinner item in android?

I have a spinner in my activity which contain Operators name ,what I want when user selected item from spinner I want to send another value to server,like
if user select "Airtel" from spinner I have to send "AR" to server same like other items .how can I do that.


<string-array name="operators">
<item>Select Operator</item>
<item>MTNL Delhi</item>
<item>MTNL Mumbai</item>

here when user select item from above list I have to send value from below list according to above items.

<string-array name="Operators_Code">

Answer Source

A Spinner, similar to ListView, RecyclerView, etc., is an "adapter backed" View. That is, it gets the items to be displayed from an Adapter.

When you set the entries to be shown using android:entries="@array/operators, Spinner internally creates an Adapter with the supplied array items. This simple solution, however, doesn't support complex objects.

For your use case, you'll have to create a custom Adapter for your Spinner.

public class Operator {
    String name;
    String code;

    public String toString() {
        return name;

final List<Operator> operators = new ArrayList(7);
operators.add(new Operator("Select operator", null));
operators.add(new Operator("Aircel", "AC"));
operators.add(new Operator("Airtel", "AC"));

Next, set the adapter on your spinner:

final ArrayAdapter<String> operatorsAdapter = new ArrayAdapter<>(context, android.R.layout.simple_dropdown_item_1line, operators);

That's it. Now if you want to listen to user's selections, add a listener to your Spinner by:

spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        final Operator selectedOperator = operatorsAdapter.getItem(position);
        final String selectedOperatorCode = selectedOperator.code;
        // TODO: Send the selected operator to the server.

    public void onNothingSelected(AdapterView<?> parent) {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download