Siddharth Siddharth - 5 months ago 21
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.

code:-\

<string-array name="operators">
<item>Select Operator</item>
<item>Aircel</item>
<item>Airtel</item>
<item>BSNL</item>
<item>Idea</item>
<item>Vodafone</item>
<item>MTNL Delhi</item>
<item>MTNL Mumbai</item>
</string-array>


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">
<item>AC</item>
<item>AT</item>
<item>BS</item>
<item>ID</item>
<item>VD</item>
<item>MT</item>
</string-array>

Answer

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;

    @Override
    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);
spinner.setAdapter(operatorsAdapter);

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() {
    @Override
    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.
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {
    }
});
Comments