如何在选择下拉列表项后获取下拉列表的值

huangapple go评论76阅读模式
英文:

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:

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

States.java

public class States {
@SerializedName(&quot;data&quot;)
@Expose
private List&lt;AllStates&gt; data = null;
@SerializedName(&quot;status&quot;)
@Expose
private Boolean status;
@SerializedName(&quot;code&quot;)
@Expose
private int code;
public States(){
}
public List&lt;AllStates&gt; getData() {
return data;
}
public void setData(List&lt;AllStates&gt; 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(&quot;id&quot;)
@Expose
private String id;
@SerializedName(&quot;name&quot;)
@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&lt;AllStates&gt; stateList = new ArrayList&lt;&gt;();
ArrayList&lt;String&gt; stateSpinnerList = new ArrayList&lt;&gt;();
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&lt;?&gt; parent, View view, int position, long id) {
String item = parent.getItemAtPosition(position).toString();
Toast.makeText(parent.getContext(), &quot;Selected: &quot; + item, Toast.LENGTH_LONG).show();
}
@Override
public void onNothingSelected(AdapterView&lt;?&gt; parent) {
}
});
Retrofit retrofit   = RetrofitClient.getInstance();
ApiService apiService = retrofit.create(ApiService.class);
apiService.allStates().subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer&lt;States&gt;() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(States states) {
stateList = states.getData();
stateSpinnerList.add(&quot;Select state&quot;);
for(int i =0;i&lt;stateList.size();i++){
stateSpinnerList.add(stateList.get(i).getName());
}
ArrayAdapter&lt;String&gt; stateAdapter = new ArrayAdapter&lt;&gt;(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&lt;String, Integer&gt; map = new HashMap&lt;&gt;();
for(state in list){
   map.put(state.name, state.id);
}

spinnerState.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView&lt;?&gt; parent, View view, int position, long id) {

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

        @Override
        public void onNothingSelected(AdapterView&lt;?&gt; 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&lt;String, Integer&gt; map = new HashMap&lt;&gt;();
for(state in list){
map.put(state.name, state.id);
}
spinnerState.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView&lt;?&gt; parent, View view, int position, long id) {
String name = parent.getItemAtPosition(position).toString();
int id = map.get(name);
}
@Override
public void onNothingSelected(AdapterView&lt;?&gt; 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&lt;?&gt; parent, View view, int position, long id) {
//      int position = spinnerState.getSelectedItemPosition();
if(position &gt;= 1){
AllStates allStates = stateList.get(position - 1)  
}
}
@Override
public void onNothingSelected(AdapterView&lt;?&gt; parent) {
}
});

Now you can access id from allStates model

huangapple
  • 本文由 发表于 2020年7月25日 17:47:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/63086853.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定