如何使用jsonOject解析多行

时间:2017-07-26 14:36:33

标签: php android mysql json

我使用 php API从 mysql 获取数据,我使用Json_encode将结果传递给android但是当我将结果填充到android listview时,我只得到一个第一行。

这是我在网上的重新发布: {"error":false,"user":{"paid_amount":"500","parking_duration":"59min","parking_name":"asass"}} {"error":false,"user":{"paid_amount":"100","parking_duration":"22min","parking_name":"SDSDASDAS"}}

PHP部分:

                       ...........
                      $usersArr = $db->getDriverHistory($plate_no);
           if ($usersArr != false) {
          foreach($usersArr as $key=>$user){
            // use is found
          $response[$key]["error"] = FALSE;
             $response[$key]["user"]["paid_amount"] = $user["paid_amount"];
             $response[$key]["user"]["parking_duration"] = 
          $user["parking_duration"];
        $response[$key]["user"]["parking_name"] = $user["parking_name"];
      $response = $response[$key] ;
         // echo json_encode($response), "<br>";
        // echo $response;        
          $json = json_encode($response);
          echo $json,"<br>";
             ......

Android代码:我需要的是获得所有结果,其中牌号等于某个数字,但我只获得一行而不是所有行。

                 private void GetParkingInfo(final String plate_no) {
               // Tag used to cancel the request
       String tag_string_req = "req_Verfication";

       progressBarList.setVisibility(View.VISIBLE);
           //        myList.setVisibility(View.GONE);

        StringRequest strReq = new StringRequest(Request.Method.POST,
            Urls.URL_driver_parking_information, new 
         Response.Listener<String>() {

        @Override
        public void onResponse(String response) {
            Log.d(TAG, "cerfication Response: " + response.toString());             
            // Parsing json
            for (int i = 0; i < response.length(); i++) {

                 try {

                     JSONObject jObj = new JSONObject(response);
                    boolean error = jObj.getBoolean("error");
                    // Check for error node in json
                    if (!error) {


                        // user successfully exist in database
                        JSONObject user = jObj.getJSONObject("user");
                        String paid_amount = user.getString("paid_amount");
                        String parking_duration = 
               user.getString("parking_duration");
                        String parking_name = user.getString("parking_name");
                        HashMap<String, String> prodHashMap = new 
                    HashMap<String, String>();

                        prodHashMap.put("paid_amount", paid_amount);
                        prodHashMap.put("parking_duration", parking_duration);
                        prodHashMap.put("parking_name", parking_name);

                        ArrayList<HashMap<String, String>> wordList;
                           wordList = new ArrayList<HashMap<String, String>>();
                        wordList.add(prodHashMap);
                        userList = wordList ;
                        ShowListData();

                        progressBarList.setVisibility(View.GONE);

                         }

                      else{

                        // Error in login. Get the error message
              //                       // hiding the progress bar
                        progressBarList.setVisibility(View.GONE);
                         myList.setVisibility(View.VISIBLE);
                        String errorMsg = jObj.getString("error_msg");
                        Toast.makeText(getApplicationContext(), errorMsg, 
               Toast.LENGTH_LONG).show();

                    }

                   } catch (JSONException e) {
                    // JSON error
                    e.printStackTrace();
                    Toast.makeText(getApplicationContext(), "Json error: " + 
             e.getMessage(), Toast.LENGTH_LONG).show();
        //                     // hiding the progress bar
                    progressBarList.setVisibility(View.GONE);
                    myList.setVisibility(View.VISIBLE);
                   }
                }
            }
              }, new Response.ErrorListener() {

           @Override
           public void onErrorResponse(VolleyError error) {
            Log.e(TAG, "Verfication error Error: " + error.getMessage());

            Toast.makeText(getApplicationContext(),
                    "response error", Toast.LENGTH_LONG).show();
          //                Toast.makeText(getApplicationContext(),
        //                        error.getMessage(), Toast.LENGTH_LONG).show();
            // hiding the progress bar
            progressBarList.setVisibility(View.GONE);
            myList.setVisibility(View.VISIBLE);
            }
             }) {
            @Override
             protected Map<String, String> getParams() {

            // Posting parameters to verfication url
            Map<String, String> params = new HashMap<String, String>();
            params.put("plate_no", plate_no);
            return params;
           }
        };
    //        // Adding request to request queue

        AppController.getInstance().addToRequestQueue(strReq,tag_string_req);
       }

3 个答案:

答案 0 :(得分:0)

您不会只获得一行,您每次迭代都会创建一个新的ArrayList。你只会以这种方式获得最后一排。

ArrayList<HashMap<String, String>> wordList;
                       wordList = new ArrayList<HashMap<String, String>>();

您需要在for循环之外初始化列表。

ArrayList<HashMap<String, String>> wordList = new ArrayList<HashMap<String, String>>();
for (int i = 0; i < response.length; i++) {

    // add your information here
}

编辑::

我知道发生了什么。你正在循环String的长度。您需要将String响应转换为JSONArray并循环遍历。这样您就可以遍历数组中的每个JSONObject

        List<HashMap<String, String>> wordList = new 
            ArrayList<HashMap<String,String>>();
        try {
           JSONArray array = new JSONArray(response);
           for (int i = 0; i < array.length(); i++) {
                JSONObject jsonObject = array.getJSONObject(i);
                // get user // do rest of work
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

编辑2 ::

这应该让你去。我还没有经过测试,所以要小心任何缺失的括号。

    private void GetParkingInfo(final String plate_no) {
    // Tag used to cancel the request
    String tag_string_req = "req_Verfication";

    progressBarList.setVisibility(View.VISIBLE);
    //        myList.setVisibility(View.GONE);

    StringRequest strReq = new StringRequest(Request.Method.POST,
            Urls.URL_driver_parking_information, new
            Response.Listener<String>() {

                @Override
                public void onResponse(String response) {
                    Log.d(TAG, "cerfication Response: " + response.toString());
                    try {
                        JSONArray jsonArray = new JSONArray(response);
                        if (jsonArray != null && !jsonArray.length() > 0) {
                            for (int i = 0; i < jsonArray.length(); i++) {
                                JSONObject jsonObject = jsonArray.getJSONObject(i);
                                if (!jsonObject.isNull("user")) {
                                    JSONObject user = jsonObject.getJSONObject("user");
                                    String paid_amount = user.getString("paid_amount");
                                    String parking_duration =
                                            user.getString("parking_duration");
                                    String parking_name = user.getString("parking_name");
                                    HashMap<String, String> prodHashMap = new
                                            HashMap<String, String>();

                                    prodHashMap.put("paid_amount", paid_amount);
                                    prodHashMap.put("parking_duration", parking_duration);
                                    prodHashMap.put("parking_name", parking_name);

                                    ArrayList<HashMap<String, String>> wordList;
                                    wordList = new ArrayList<HashMap<String, String>>();
                                    wordList.add(prodHashMap);
                                    userList = wordList ;
                                    ShowListData();

                                    progressBarList.setVisibility(View.GONE);
                                }
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                        Toast.makeText(getApplicationContext(), "Json error: " +
                                e.getMessage(), Toast.LENGTH_LONG).show();
                        //                     // hiding the progress bar
                        progressBarList.setVisibility(View.GONE);
                        myList.setVisibility(View.VISIBLE);
                    }
                }
            }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            Log.e(TAG, "Verfication error Error: " + error.getMessage());

            Toast.makeText(getApplicationContext(),
                    "response error", Toast.LENGTH_LONG).show();
            //                Toast.makeText(getApplicationContext(),
            //                        error.getMessage(), Toast.LENGTH_LONG).show();
            // hiding the progress bar
            progressBarList.setVisibility(View.GONE);
            myList.setVisibility(View.VISIBLE);
        }
    }) {
        @Override
        protected Map<String, String> getParams() {

            // Posting parameters to verfication url
            Map<String, String> params = new HashMap<String, String>();
            params.put("plate_no", plate_no);
            return params;
        }
    };
    //        // Adding request to request queue

    AppController.getInstance().addToRequestQueue(strReq,tag_string_req);
}

编辑3 ::

if ($usersArr != false) { 
    foreach($usersArr as $user){
        $subresponse["error"] = FALSE; 
        $subresponse["user"]["paid_amount"] = $user["paid_amount"];
        $subresponse["user"]["parking_duration"] = $user["parking_duration"]; 
        $subresponse["user"]["parking_name"] = $user["parking_name"];
        $response[] = $subresponse;
        $json = json_encode($response);

我认为应该看起来

  if ($usersArr != false) { 
       foreach($usersArr as $user){
           $subresponse["error"] = FALSE; 
           $subresponse["user"]["paid_amount"] = $user["paid_amount"];
           $subresponse["user"]["parking_duration"] = $user["parking_duration"]; 
           $subresponse["user"]["parking_name"] = $user["parking_name"];
           $response[] = $subresponse;
      } 
      $json = json_encode($response);

答案 1 :(得分:0)

您已在错误的位置初始化了集合,请查看以下代码,这可能会对您有所帮助

 ArrayList<HashMap<String, String>> wordList;
            wordList = new ArrayList<HashMap<String, String>>();

            for (int i = 0; i < response.length(); i++) {

                try {

                    JSONObject jObj = new JSONObject(response);
                    boolean error = jObj.getBoolean("error");
                    // Check for error node in json
                    if (!error) {


                        // user successfully exist in database
                        JSONObject user = jObj.getJSONObject("user");
                        String paid_amount = user.getString("paid_amount");
                        String parking_duration =
                                user.getString("parking_duration");
                        String parking_name = user.getString("parking_name");
                        HashMap<String, String> prodHashMap = new
                                HashMap<String, String>();

                        prodHashMap.put("paid_amount", paid_amount);
                        prodHashMap.put("parking_duration", parking_duration);
                        prodHashMap.put("parking_name", parking_name);


                        wordList.add(prodHashMap);
                        ;

                        progressBarList.setVisibility(View.GONE);

                    }

                    userList = wordList ;
                    ShowListData()

答案 2 :(得分:0)

此解决方案将帮助任何需要使用where子句基于android输入和volley库从mysql获取数据的人。

处理php函数的DBHandler:

                     .....
               public function getDriverHistory($plate_no) {
             $stmt = $this->conn->prepare("SELECT * from drivers_history 
           where  drivers_history.plate_no = ?");

          $stmt->bind_param("s", $plate_no);
           if ($stmt->execute()) {

           //  $user = $stmt->get_result()->fetch_assoc();       
           //  $stmt->close();
           // return $user;

         $result = $stmt->get_result();
          $usersArr = array();
         while ($user = $result->fetch_assoc()){
        $usersArr[] = $user;
         }
          $stmt->close();
         return $usersArr;


         } else {
        return NULL;
         }
         }
             ....

GetdriverFunction.php用于访问上面的函数:

                                      ...........

           <?php
               include './DbHandler.php';
              $db = new DBHandler(); 
          // json response array
        $response = array("error" => FALSE); 
            if (isset($_POST['plate_no'])) {
              // receiving the post params
                 $plate_no = $_POST['plate_no']; 
                  $usersArr = $db->getDriverHistory($plate_no);
              if ($usersArr != false) {
            $response["error"]= FALSE;
          $response["user"] = $usersArr;
         echo json_encode($response); 
              }
             }
         ......

最后用Java部分方法获取所有结果,其中plate_no等于某个plate_no:

              private void GetParkingInfo(final String plate_no) {
           // Tag used to cancel the request
             String tag_string_req = "req_Verfication";

   progressBarList.setVisibility(View.VISIBLE);
       //        myList.setVisibility(View.GONE);

    StringRequest strReq = new StringRequest(Request.Method.POST,
        Urls.URL_driver_parking_information, new 
     Response.Listener<String>() {

    @Override
    public void onResponse(String response) {
        Log.d(TAG, "cerfication Response: " + response.toString());             
        // Parsing json
        JSONArray jsonArrayResult ;
        for (int i = 0; i < response.length(); i++) {

             try {

                 JSONObject jObj = new JSONObject(response);
                boolean error = jObj.getBoolean("error");
                // Check for error node in json
                if (!error) {


                    // user successfully exist in database

                      jsonArrayResult = jObj.getJSONArray("user");

                for(int x=0; x<jsonArrayResult.length();x++){

                     JSONObject json = jsonArrayResult.getJSONObject(x);


                    String paid_amount = json.getString("paid_amount");
                    String parking_duration = 
           json.getString("parking_duration");
                    String parking_name = json.getString("parking_name");
                    HashMap<String, String> prodHashMap = new 
                HashMap<String, String>();

                    prodHashMap.put("paid_amount", paid_amount);
                    prodHashMap.put("parking_duration", parking_duration);
                    prodHashMap.put("parking_name", parking_name);

                    ArrayList<HashMap<String, String>> wordList;
                       wordList = new ArrayList<HashMap<String, String>>();
                    wordList.add(prodHashMap);
                    userList = wordList ;
                    }
                    ShowListData();

                    progressBarList.setVisibility(View.GONE);

                     }

                  else{

                    // Error in login. Get the error message
          //                       // hiding the progress bar
                    progressBarList.setVisibility(View.GONE);
                     myList.setVisibility(View.VISIBLE);
                    String errorMsg = jObj.getString("error_msg");
                    Toast.makeText(getApplicationContext(), errorMsg, 
           Toast.LENGTH_LONG).show();

                }

               } catch (JSONException e) {
                // JSON error
                e.printStackTrace();
                Toast.makeText(getApplicationContext(), "Json error: " + 
         e.getMessage(), Toast.LENGTH_LONG).show();
    //                     // hiding the progress bar
                progressBarList.setVisibility(View.GONE);
                myList.setVisibility(View.VISIBLE);
               }
            }
        }
          }, new Response.ErrorListener() {

       @Override
       public void onErrorResponse(VolleyError error) {
        Log.e(TAG, "Verfication error Error: " + error.getMessage());

        Toast.makeText(getApplicationContext(),
                "response error", Toast.LENGTH_LONG).show();
      //                Toast.makeText(getApplicationContext(),
    //                        error.getMessage(), Toast.LENGTH_LONG).show();
        // hiding the progress bar
        progressBarList.setVisibility(View.GONE);
        myList.setVisibility(View.VISIBLE);
        }
         }) {
        @Override
         protected Map<String, String> getParams() {

        // Posting parameters to verfication url
        Map<String, String> params = new HashMap<String, String>();
        params.put("plate_no", plate_no);
        return params;
       }
    };
//        // Adding request to request queue

    AppController.getInstance().addToRequestQueue(strReq,tag_string_req);
   }