使用齐射检索json对象列表

时间:2017-03-08 10:23:23

标签: android json android-volley android-json

我需要从mysql数据库中检索json对象列表,使用volley解析它并用它填充listview。我是php和凌空的新手。这就是我的尝试方式。

JSON:

 JSONArray sts;
public static final String STUDENT_URL = "http://www.smartlbus.esy.es/getAllStudents.php";
        students=new ArrayList<Student>();
                StringRequest stringRequest = new StringRequest(STUDENT_URL, new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                                JSONObject jsonObject=null;
                                jsonObject = new JSONObject(response);
                                sts = jsonObject.getJSONArray(JSON_ARRAY);

                                for (int i = 0; i < sts.length(); i++) {
                                    JSONObject jo = sts.getJSONObject(i);
                                    Student s=new Student();
                                    Toast.makeText(StudentDetails.this,jo.getString(STUDENT_NAME),Toast.LENGTH_SHORT).show();
                                    s.setId(jo.getString(STUDENT_ID));
                                    s.setName(jo.getString(STUDENT_NAME));
                                    s.setClassNo(jo.getString(STUDENT_CLASS));
                                    s.setBusno(jo.getString(STUDENT_BUS));
                                    s.setStatus(Integer.parseInt(jo.getString(STUDENT_STATUS)));
                                    s.setStopid(jo.getString(STUDENT_STOP));
                                    students.add(s);
                                }
                        }
                        catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        error.printStackTrace();
                    }
                });


                RequestQueue requestQueue = Volley.newRequestQueue(this);
                requestQueue.add(stringRequest);
                listView.setAdapter(new CustomListAdapter(StudentDetails.this,students));

机器人:

alterStock(stockRelatedData) {

if (stockRelatedData.departmentID === null || stockRelatedData.itemID === null || stockRelatedData.stock === null) {
  return Observable.throw("Please insert details");
} else {
  return Observable.create(observer => {

    let headers = new Headers({
      'Content-Type': 'application/x-www-form-urlencoded'
    });
    let options = new RequestOptions({
      headers: headers
    });

        // TODO: Encode the values using encodeURIComponent().
    var link = 'http://ims/api/inventory/alterstock?api_token='+ stockRelatedData.apiToken;
    var data = JSON.stringify({department_id: stockRelatedData.departmentID, item_id: stockRelatedData.itemID, stock: stockRelatedData.stock, api_token: stockRelatedData.apiToken, location_id: stockRelatedData.locationID, user_id: stockRelatedData.userID});
    this.http.post(link, data, options)
    .subscribe(result => {

        this.data = result;
        this.data = JSON.parse(this.data._body);

        let access = this.data.status;
        observer.next(access);
        observer.complete();
    }, error => {
        console.log("Oooops!");
    });

  });
}

请帮帮我。如果这不符合此处的标准,请发表评论并告诉我。我会把它拿下来。

2 个答案:

答案 0 :(得分:0)

尝试使用Gson来简化您的开发。

创建Java POJO类:

public class StudentList {
    List<Student> results;
    // setter

    public static class Student {
          String name;
          String id;
          String status;
          String class;
          String stopid;
          String busno;
        // getter
    }
}

然后使用onResponse()方法中的GSON解析它们。 我建议使用Retrofit进行网络通话。

Gson gson = new Gson();
StudentList list = gson.fromJson(response);
// populate to ListView using list.getResults()

答案 1 :(得分:0)

试试这个&amp;还要检查你的网址。你的网址没有返回任何json响应。

        StringRequest stringRequest = new StringRequest(Request.Method.GET,STUDENT_URL ,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                                Log.d("TAG","response :"+response);
                                JSONObject jsonObject = new JSONObject(response);
                                sts = jsonObject.getJSONArray(JSON_ARRAY);

                                for (int i = 0; i < sts.length(); i++) {
                                    JSONObject jo = sts.getJSONObject(i);
                                    Student s=new Student();
                                    Log.d("TAG","Name :"+jo.getString(STUDENT_NAME));
                                   // Toast.makeText(StudentDetails.this,jo.getString(STUDENT_NAME),Toast.LENGTH_SHORT).show();
                                    s.setId(jo.getString(STUDENT_ID));
                                    s.setName(jo.getString(STUDENT_NAME));
                                    s.setClassNo(jo.getString(STUDENT_CLASS));
                                    s.setBusno(jo.getString(STUDENT_BUS));
                                    s.setStatus(Integer.parseInt(jo.getString(STUDENT_STATUS)));
                                    s.setStopid(jo.getString(STUDENT_STOP));
                                    students.add(s);
                                }
                        } catch (JSONException e) {
                             e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        e.printStackTrace();
                    }
                });
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);