无法将GroupModel强制转换为另一个模型

时间:2019-01-22 07:46:52

标签: android json android-spinner

我试图将数据从Web服务拉到链接的微调器,而没有数据同时拉到两个微调器。代码的这一部分给出了一个错误:

spinnerFleet.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
            FleetModel selectedItem = (FleetModel) adapterView.getSelectedItem(); /*I think there was an error in this part of the code */
            int vgID = displayIdData(selectedItem);
            String jsonString = "{\"params1\":\"" + session_id + "\"," +
                    "\"params2\":\"5\"," +
                    "\"params3\":\"0\"," +
                    "\"params4\":\"0\"," +
                    "\"params5\":\"0\"," +
                    "\"params6\":\""+vgID+"\"," +
                    "\"params7\":\"0\"," +
                    "\"params8\":\"" + user_id + "\"}";
            new LoadSpinnerGroupTask().execute(jsonString);
        }

1 个答案:

答案 0 :(得分:0)

显然,adapterView.getSelectedItem()返回GroupModel,而不是FleetModel。因此,如果FleetModel不扩展GroupModel,它将抛出强制转换错误。

适配器项中的数据类型是什么?将其更改为FleetModel,或只写GroupModel selectedItem = (GroupModel) adapterView.getSelectedItem();

像这样尝试:

spinnerFleet.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
            FleetModel selectedItem = stateAdapter.getItem(i); /*I think there was an error in this part of the code */
            int vgID = displayIdData(selectedItem);
            String jsonString = "{\"params1\":\"" + session_id + "\"," +
                    "\"params2\":\"5\"," +
                    "\"params3\":\"0\"," +
                    "\"params4\":\"0\"," +
                    "\"params5\":\"0\"," +
                    "\"params6\":\""+vgID+"\"," +
                    "\"params7\":\"0\"," +
                    "\"params8\":\"" + user_id + "\"}";
            new LoadSpinnerGroupTask().execute(jsonString);
        }