How to parse multiple rows with jsonOject

前端 未结 3 1906
有刺的猬
有刺的猬 2021-01-23 15:49

I am fetching data from mysql using php API and i pass results to android with Json_encode but when i populate results to android

相关标签:
3条回答
  • 2021-01-23 16:33

    This solution will help anyone who needds to fetch data from mysql using where clause based to android input with volley library .

    DBHandler which handles php functions :

                         .....
                   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 used to access function above :

                                          ...........
    
               <?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); 
                  }
                 }
             ......
    

    finally Java part method to fetch all results where plate_no equals to something 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);
       }   
    
    0 讨论(0)
  • 2021-01-23 16:37

    You have initialized collection in wrong place, Please have look at following code this may help you

     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()
    
    0 讨论(0)
  • 2021-01-23 16:37

    You aren't getting just one row, you're creating a new ArrayList through every iteration. You'll only ever get the last row this way.

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

    You need to initialize your list outside your for loop.

    ArrayList<HashMap<String, String>> wordList = new ArrayList<HashMap<String, String>>();
    for (int i = 0; i < response.length; i++) {
    
        // add your information here
    }
    

    Edit::

    I see what's happening. You're looping for the length of String. You need to convert your String response to a JSONArray and loop through that. This way you step through each JSONObject in the array

            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();
            }
    

    Edit 2::

    This should get you going. I haven't tested, so watch out for any missing brackets.

        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);
    }
    

    Edit 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);
    

    how I think it should look

      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);
    
    0 讨论(0)
提交回复
热议问题