json data sample我正在从json加载标签名称,当我尝试获取每个标签的数据时,我只得到关于最后一只兔子的数据 这是代码
final TabLayout tabLayout = (TabLayout) view.findViewById(R.id.tabLayout);
final RequestQueue catRequestQueue = Volley.newRequestQueue(getActivity());
JsonArrayRequest catJsonArrayRequest = new JsonArrayRequest(Request.Method.GET, Utils.BASE_URL + "getCats"
, null, new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
for (int i = 0; i < response.length(); i++) {
CategoryModel categoryModel = new CategoryModel();
try {
JSONObject jsonObject = response.getJSONObject(i);
categoryModel.setName(jsonObject.getString("name"));
categoryModel.setId(jsonObject.getString("id"));
tabLayout.addTab(tabLayout.newTab().setText(categoryModel.getName()), false);
} catch (JSONException e) {
e.printStackTrace();
}
catId = categoryModel.getId();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
catRequestQueue.add(catJsonArrayRequest);
CategoryModel类
公共类CategoryModel实现Serializable {
private String id;
private String name;
private String parent;
private String photo;
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;
}
public String getParent() {
return parent;
}
public void setParent(String parent) {
this.parent = parent;
}
public String getPhoto() {
return photo;
}
public void setPhoto(String photo) {
this.photo = photo;
}
}
修改
categoryModelArrayList = new ArrayList<>();
final TabLayout tabLayout = (TabLayout) view.findViewById(R.id.tabLayout);
final RequestQueue catRequestQueue = Volley.newRequestQueue(getActivity());
JsonArrayRequest catJsonArrayRequest = new JsonArrayRequest(Request.Method.GET, Utils.BASE_URL + "getCats"
, null, new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
for (int i = 0; i < response.length(); i++) {
CategoryModel categoryModel = new CategoryModel();
try {
JSONObject jsonObject = response.getJSONObject(i);
categoryModel.setName(jsonObject.getString("name"));
categoryModel.setId(jsonObject.getString("id"));
categoryModelArrayList.add(categoryModel);
tabLayout.addTab(tabLayout.newTab().setText(categoryModel.getName()), false);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
catRequestQueue.add(catJsonArrayRequest);
答案 0 :(得分:0)
可能存在异常,为什么尝试解析JSON,阻止添加标签。
此外正如@Mike M.所说,你有catId = categoryModel.getId();
INSIDE the loop,因此,只保留最后一个实例。
如果您需要所有ID,请使用列表,出于调试目的,我建议您删除try-catch语法,以确保循环完全执行而不会引发异常,或澄清您的问题说没有例外。