当我使用自定义适配器使用json时,应用程序崩溃了

时间:2017-11-15 09:45:35

标签: java android json spinner

  

java.lang.IndexOutOfBoundsException:索引0无效,大小为0 in   旋转器

   public void GetAllData() {
        JsonObjectRequest request=new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                try {
                    ArrayList<CityList>mylist=new ArrayList<CityList>();
                    JSONArray array=response.getJSONArray("data");
                    for(int index=0;index<array.length();index++)
                    {
                        JSONObject object=array.getJSONObject(index);
                        mylist.add(new CityList(object.getInt("id"),object.getString("name")));
                    }
                    CityAdapter cityAdapter=new CityAdapter(MainActivity.this,R.layout.custome_spinner,R.id.humanmed,mylist);
                    ServiceName.setAdapter(cityAdapter);
                } catch (JSONException e) {
                    Toast.makeText(MainActivity.this, "bad", Toast.LENGTH_SHORT).show();        }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(MainActivity.this, "sad", Toast.LENGTH_SHORT).show();
            }
        });

2 个答案:

答案 0 :(得分:0)

而不是:

ArrayList<CityList>mylist=new ArrayList<CityList>();

使用:

ArrayList<City>mylist=new ArrayList<City>();

而不是:

mylist.add(new CityList(object.getInt("id"),object.getString("name")));

使用:

City city = new City();
city.setId(object.getInt("id"));
city.setName = (object.getString("name"));

mylist.add(city);

您还必须将课程城市设为:

public class City {

private int id;

private String name;

public int getId() {
    return id;
}

public void setId(Int id) {
    this.id = id;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

}

将类CityList创建为:

public class CityList {

private List<City> cities;


public List<City> getCities() {
    return cities;
}

public void setCities(List<City> cities) {
    this.cities = cities;
}

}

答案 1 :(得分:0)

仅将此添加到您的自定义适配器微调器将起作用

@覆盖     public View getDropDownView(int position,@ Nullable View convertView,@ NonNull ViewGroup parent){         return getView(position,convertView,parent);     }