Search code examples
javaandroidretrofit2android-spinner

How to get spinner value after item select in spinner


I am using spinner in my app I am populating spinner with the data fetching from the server.I am using Retrofit2 as a networking library. There are 2 values I am fetching from the server one is state name and other is state id.

In spinner I am showing state name, but on select state it should select corresponding state name id that I have fetched from the server. In spinner state name is showing successfully but I want to gets corresponding state name id that I have in POJO class and not item position.

Below is my code:

Server response is given below:

{
"data": [
    {
        "id": "5",
        "name": "Bihar"
    },
    {
        "id": "7",
        "name": "Chhattisgarh"
    },
    {
        "id": "10",
        "name": "Delhi"
    }
],
"status": true,
"code": 200
} 

 

States.java

public class States {

@SerializedName("data")
@Expose
private List<AllStates> data = null;
@SerializedName("status")
@Expose
private Boolean status;
@SerializedName("code")
@Expose
private int code;

public States(){

}

public List<AllStates> getData() {
    return data;
}

public void setData(List<AllStates> data) {
    this.data = data;
}

public Boolean getStatus() {
    return status;
}

public void setStatus(Boolean status) {
    this.status = status;
}

public int getCode() {
    return code;
}

public void setCode(int code) {
    this.code = code;
}
}

AllStates.java

public class AllStates {

@SerializedName("id")
@Expose
private String id;
@SerializedName("name")
@Expose
private String name;

public AllStates(){

}

public String getId() {
    return id;
}

public void setId(String id) {
    this.id = id;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}
}

CalenderFragment.java

public class CalendarFragment extends Fragment {

Spinner spinnerState;
List<AllStates> stateList = new ArrayList<>();
ArrayList<String> stateSpinnerList = new ArrayList<>();

public CalendarFragment() {
    // Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_calendar, container, false);

    spinnerState = view.findViewById(R.id.spinnerState);

    spinnerState.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

            String item = parent.getItemAtPosition(position).toString();
            Toast.makeText(parent.getContext(), "Selected: " + item, Toast.LENGTH_LONG).show();
        }

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

        }
    });

    Retrofit retrofit   = RetrofitClient.getInstance();
    ApiService apiService = retrofit.create(ApiService.class);

    apiService.allStates().subscribeOn(Schedulers.io())
                          .observeOn(AndroidSchedulers.mainThread())
                          .subscribe(new Observer<States>() {
                              @Override
                              public void onSubscribe(Disposable d) {

                              }

                              @Override
                              public void onNext(States states) {

                                 stateList = states.getData();

                                 stateSpinnerList.add("Select state");

                                 for(int i =0;i<stateList.size();i++){

                                     stateSpinnerList.add(stateList.get(i).getName());
                                 }

                                 ArrayAdapter<String> stateAdapter = new ArrayAdapter<>(getActivity(),android.R.layout.simple_list_item_1,stateSpinnerList);
                                 spinnerState.setAdapter(stateAdapter);
                              }

                              @Override
                              public void onError(Throwable e) {

                                  TastyToast.makeText(getActivity(),e.getMessage(),TastyToast.LENGTH_SHORT,
                                                           TastyToast.ERROR).show();
                              }

                              @Override
                              public void onComplete() {

                              }
                          });

    return view;
  }
}

How can I get the desired result?


Solution

  • If you don't want to use a custom adapter then fetch selected spinner position and using that position fetch your State model

        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
              //      int position = spinnerState.getSelectedItemPosition();
    
                   if(position >= 1){
                       AllStates allStates = stateList.get(position - 1)  
                   }
            }
    
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
    
            }
        });
    

    Now you can access id from allStates model