无法使用齐射从数据库中检索数据

时间:2017-04-02 08:39:14

标签: php android mysql json android-volley

我想在MySQL中从表中检索多个元组。我正在使用排球。我想将收到的数据附加到textview。我收到Volley.Server错误。 volley和JSon请求的代码如下

    private void active1(){
    StringRequest stringRequest = new StringRequest(Request.Method.POST, JSON_URL,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    Toast.makeText(bossmain.this, response, Toast.LENGTH_LONG).show();
                    showJSON(response);
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(bossmain.this,error.toString(),Toast.LENGTH_LONG).show();
                }
            }){
        @Override
        protected Map<String,String> getParams(){
            Map<String,String> params = new HashMap<String, String>();
            params.put(KEY_USERNAME,usernameb);
            params.put(KEY_ACTIVE,active);
            return params;
        }
    };

    RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(stringRequest);
}

private void showJSON(String response){
    String name="";
    try {
        JSONObject jsonObject = new JSONObject(response);
        JSONArray result = jsonObject.getJSONArray("workers");
        for(int i=0;i<result.length();i++) {
            JSONObject worker = result.getJSONObject(i);
            name = worker.getString("username");
            lv.append(name+"\n");
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

}

我已将PHP用于脚本,其代码如下:

    <?php
    $bossname =$_POST['username'];
    $active =$_POST['active'];

    require_once('dbConnect.php');

    $sql=mysqli_query($conn,"SELECT username FROM Employee WHERE bossname='$bossname' AND active='$active'");
    if($sql){
while($row=mysqli_fetch_assoc($sql)){
    $workers[]=$row;
}
print(json_encode($workers[]));
    }
    mysqli_close($con);
    ?>

欢迎所有建议。谢谢。

1 个答案:

答案 0 :(得分:0)

尝试将PHP API代码更改为:

$res = array(); 
while($row = mysqli_fetch_array($sql)){
     array_push($res, array(
     "username"=>$row['workers']['username']
     ));
     }

echo json_encode($res, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_ERROR_UTF8);

和你的showJSON方法一样smthng:

private void showJSON(String response){
JSONObject jsonObject=null;
    try {
        jsonObject = new JSONObject(response);
        JSONArray result = jsonObject.getJSONArray("workers");
        workers = new String[result.length()];

        for(int i=0;i<result.length();i++) {
            JSONObject worker = result.getJSONObject(i);
            workers[i] = worker.getString("username");

        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

}