我试图填充从mysql/rest服务的数据旋转器。我只想在spinner中显示所有员工的id。在下拉框中,我看到id与值和其他列作为名称:null,年龄:null等。但是在选择一个之后,我可以通过在我的旋转器适配器类上获得id值来单独显示id值。如何在下拉框上显示id值?
@Override
public void onSuccess(int statusCode, Header[] headers, JSONArray response) {
ArrayList<Employee> spinnerArray = new ArrayList<Employee>();
final SpinnerAdapter spinnerAdapter = new SpinnerAdapter(MainActivity.this, spinnerArray);
for (int i = 0; i < response.length(); i++)
{
try {
spinnerAdapter.add(new Employee(response.getJSONObject(i)));
}
catch (JSONException e) {
e.printStackTrace();
}
}
spinner.setAdapter(spinnerAdapter);
适配器类
public class SpinnerAdapter extends ArrayAdapter<Employee> {
public SpinnerAdapter(Context context, ArrayList<Employee> employees) {
super(context, R.layout.spinner_id, employees);
}
private static class ViewHolder {
TextView employeeId;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
Employee employee = getItem(position);
ViewHolder viewHolder;
if (convertView == null) {
viewHolder = new ViewHolder();
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.spinner_id, parent, false);
viewHolder.employeeId = (TextView) convertView.findViewById(R.id.value_employee_employeeId);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.employeeId.setText(employee.getEmployeeId());
return convertView;
}
你做错了几件事。首先用json响应填充数组。如果你想要显示ID,也许你应该考虑使用字符串数组("ID")。
ArrayList<String> spinnerArray = new ArrayList<String>();
for (int i = 0; i < response.length(); i++) {
try {
spinnerArray.add(new Employee(response.getJSONObject(i)).getID());
}
catch (JSONException e) {
e.printStackTrace();
}
}
之后初始化适配器
final SpinnerAdapter spinnerAdapter = new SpinnerAdapter(MainActivity.this, spinnerArray);
最后将适配器设置为
spinner.setAdapter(spinnerAdapter);
将你的项目添加到你的ArrayList中,它是spinnerArray,而不是spinnerAdapter。数组是存放数据的地方。
spinnerArray.add(new Employee(response.getJSONObject(i)));
EDIT:取每个数据的Id
String TAG = this.getClass().getSimpleName();
for(Employee employee : spinnerArray){
Log.d("TAG", employee.getEmployeeId());
}
我不知道你的Employee.class是什么样的,但是我希望你能有个大概的概念。