Class 对微调项选择抛出异常
Class cast exception on spinner item selection
我有一个装有自定义适配器的微调器。
我用来将数据绑定到微调器的代码是
private void setOperatorSpinnerAdapter(Spinner spinner, String data) {
listOperator = new ArrayList<>();
try {
jsonObject = new JSONObject(data);
jsonArray = jsonObject.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
model2 = new LiabModel();
model2.setName(jsonObject.optString("name"));
listOperator.add(model2);
}
} catch (JSONException e) {
e.printStackTrace();
}
adapter_liab = new CustomListAdapter_liab(LiabilitiesActivity.this, listOperator);
spinner.setAdapter(adapter_liab);
}
我的问题是项目选择。我收到错误消息
java.lang.ClassCastException: java.lang.Integer 无法转换为 Model.LiabModel
我的微调器项目点击代码是
spnr.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
try {
LiabModel model2 = (LiabModel) parent.getItemAtPosition(position);
liab_type = model2.getName();
}
catch (Exception e){
Log.e("exc",""+e);
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
我得到 Class 转换异常
"LiabModel model2 = (LiabModel) parent.getItemAtPosition(position);" 这一行。为什么会这样?
您可以通过此
获取选定的值
LiabModel model2 = (LiabModel) spnr.getItemAtPosition(position);
或如果 listOperator 可访问
LiabModel model2 = listOperator.get(位置);
我有一个装有自定义适配器的微调器。
我用来将数据绑定到微调器的代码是
private void setOperatorSpinnerAdapter(Spinner spinner, String data) {
listOperator = new ArrayList<>();
try {
jsonObject = new JSONObject(data);
jsonArray = jsonObject.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
model2 = new LiabModel();
model2.setName(jsonObject.optString("name"));
listOperator.add(model2);
}
} catch (JSONException e) {
e.printStackTrace();
}
adapter_liab = new CustomListAdapter_liab(LiabilitiesActivity.this, listOperator);
spinner.setAdapter(adapter_liab);
}
我的问题是项目选择。我收到错误消息
java.lang.ClassCastException: java.lang.Integer 无法转换为 Model.LiabModel
我的微调器项目点击代码是
spnr.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
try {
LiabModel model2 = (LiabModel) parent.getItemAtPosition(position);
liab_type = model2.getName();
}
catch (Exception e){
Log.e("exc",""+e);
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
我得到 Class 转换异常 "LiabModel model2 = (LiabModel) parent.getItemAtPosition(position);" 这一行。为什么会这样?
您可以通过此
获取选定的值 LiabModel model2 = (LiabModel) spnr.getItemAtPosition(position);
或如果 listOperator 可访问
LiabModel model2 = listOperator.get(位置);