英文:
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) {
                // Get the selected state object
                AllStates selectedState = stateList.get(position);
                // Now you can access the state's ID and Name
                String stateId = selectedState.getId();
                String stateName = selectedState.getName();
                Toast.makeText(parent.getContext(), "Selected: " + stateName + " (ID: " + stateId + ")", 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?
英文:
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?
答案1
得分: 3
所以我理解的是,您正在从 Spinner 中选择州,并获取州的名称,但您想要获取 stateId。
我能想到的一个可能的解决方案是使用 HashMap<StateName, StateId> 映射。
当您从 Spinner 接收州的名称时,只需调用 map.get(name),您就会获得 state Id。
编辑:
您可以像这样实现它:
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) {
        }
    });
英文:
So what I understand is you are selecting state from Spinner and getting name of state but you want to get stateId.
one possible solution, I can think of is to use HashMap<StateName, StateId> map.
when you receive state name from spinner just call map.get(name) and you will get 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) {
}
});
答案2
得分: 1
如果您不想使用自定义适配器,那么可以获取所选微调器位置,并使用该位置获取您的 "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) {
    }
});
现在您可以从 "allStates" 模型中访问 "id"。
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论