简体   繁体   English

如何在微调器中的项目 select 之后获取微调器值

[英]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.我在我的应用程序中使用微调器我正在使用从服务器获取的数据填充微调器。我使用 Retrofit2 作为网络库。 There are 2 values I am fetching from the server one is state name and other is state id.我从服务器获取了 2 个值,一个是 state 名称,另一个是 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 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.在微调器 state 名称显示成功,但我想获得相应的 state 名称 ID,我在 POJO class 而不是项目 state

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州.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 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日历片段.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?我怎样才能得到想要的结果?

So what I understand is you are selecting state from Spinner and getting name of state but you want to get stateId.所以我的理解是你正在从 Spinner 选择 state 并获得 state 的名称,但你想获得 stateId。

one possible solution, I can think of is to use HashMap<StateName, StateId> map.我能想到的一种可能的解决方案是使用 HashMap<StateName, StateId> map。 when you receive state name from spinner just call map.get(name) and you will get state Id.当您从微调器收到 state 名称时,只需调用 map.get(name),您将获得 state Id。

Edit:编辑:

you can implement it like this你可以像这样实现它

HashMap<String, Integer> map = new HashMap<>();
for(state in list){
   map.put(state.name, state.id);
}

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

            String name = parent.getItemAtPosition(position).toString();
            int id = map.get(name);
        }

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

        }
    });

If you don't want to use a custom adapter then fetch selected spinner position and using that position fetch your State model如果您不想使用自定义适配器,请获取选定的微调器 position 并使用该 position 获取您的State

    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现在您可以从allStates model 访问id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM