Android - how to get another value of selected ite

2020-04-18 09:04发布

问题:

I've a rest response as below, and i need to populate the output to spinner. I've been successfully pass the "name" to spinner and it's works. But I also need get the "id" so I can use the "id" for query to the another rest request. for example, I get the Province id, and then I use the Province id to get the City list.

{
"code": 1000,
"message": "OK",
"data": [
    {
        "id": "3579010",
        "name": "Batu"
    },
    {
        "id": "3579020",
        "name": "Junrejo"
    },
    {
        "id": "3579030",
        "name": "Bumiaji"
    }
  ]
}

Below is the android code

public void initProvinceSpinner() {

    Call<GetProvinceResponse> call = apiService.getProvinceResponse();
    call.enqueue(new Callback<GetProvinceResponse>() {

        @Override
        public void onResponse(Call<GetProvinceResponse> call, Response<GetProvinceResponse> response) {

            ArrayList<GetProvinceResponseData> provinceResponseData = response.body().getData();
            List<String> listProvinceNameSpinner = new ArrayList<String>();
            //List<String> listProvinceIdSpinner = new ArrayList<String>();

            for(int i = 0; i<provinceResponseData.size();i++){
                listProvinceNameSpinner.add(provinceResponseData.get(i).getName());
            }

            ArrayAdapter<String> adapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_spinner_dropdown_item, listProvinceNameSpinner);
            provinceToko.setAdapter(adapter);

        }

        @Override
        public void onFailure(Call<GetProvinceResponse> call, Throwable t) {

        }
    });
}

回答1:

Try this

To get ID :

provinceResponseData.get(spinner.getSelectedItemPosition()).getId();

Add spinner listener :

spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
    @Override
    public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
        // call the service and pass the parameter
        serviceCall(provinceResponseData.get(spinner.getSelectedItemPosition()).getId());
    }

    @Override
    public void onNothingSelected(AdapterView<?> parentView) {
        // your code here
    }

});