Skip to content Skip to sidebar Skip to footer

How To Parse Multiple Rows With Jsonoject

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 listview i get only one first row. This is reuslt

Solution 1:

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

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

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

                try {

                    JSONObject jObj = newJSONObject(response);
                    boolean error = jObj.getBoolean("error");
                    // Check for error node in jsonif (!error) {


                        // user successfully exist in databaseJSONObject 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 = newHashMap<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()

Solution 2:

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 = newArrayList<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 = newArrayList<HashMap<String,String>>();
        try {
           JSONArray array = newJSONArray(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.

privatevoidGetParkingInfo(final String plate_no) {
    // Tag used to cancel the requestString tag_string_req = "req_Verfication";

    progressBarList.setVisibility(View.VISIBLE);
    //        myList.setVisibility(View.GONE);StringRequest strReq = newStringRequest(Request.Method.POST,
            Urls.URL_driver_parking_information, newResponse.Listener<String>() {

                @OverridepublicvoidonResponse(String response) {
                    Log.d(TAG, "cerfication Response: " + response.toString());
                    try {
                        JSONArray jsonArray = newJSONArray(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 = newHashMap<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 = newArrayList<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);
                    }
                }
            }, newResponse.ErrorListener() {

        @OverridepublicvoidonErrorResponse(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);
        }
    }) {
        @OverrideprotectedMap<String, String> getParams() {

            // Posting parameters to verfication urlMap<String, String> params = newHashMap<String, String>();
            params.put("plate_no", plate_no);
            return params;
        }
    };
    //        // Adding request to request queueAppController.getInstance().addToRequestQueue(strReq,tag_string_req);
}

Edit 3::

if ($usersArr != false) { 
    foreach($usersArras$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($usersArras$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);

Solution 3:

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 :

                     .....
               publicfunctiongetDriverHistory($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 {
        returnNULL;
         }
         }
             ....

GetdriverFunction.php used to access function above :

                                      ...........

           <?phpinclude'./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 :

privatevoidGetParkingInfo(final String plate_no) {
           // Tag used to cancel the requestString tag_string_req = "req_Verfication";

   progressBarList.setVisibility(View.VISIBLE);
       //        myList.setVisibility(View.GONE);StringRequest strReq = newStringRequest(Request.Method.POST,
        Urls.URL_driver_parking_information, newResponse.Listener<String>() {

    @OverridepublicvoidonResponse(String response) {
        Log.d(TAG, "cerfication Response: " + response.toString());             
        // Parsing jsonJSONArray jsonArrayResult ;
        for (int i = 0; i < response.length(); i++) {

             try {

                 JSONObject jObj = newJSONObject(response);
                boolean error = jObj.getBoolean("error");
                // Check for error node in jsonif (!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 = newHashMap<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 = newArrayList<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);
               }
            }
        }
          }, newResponse.ErrorListener() {

       @OverridepublicvoidonErrorResponse(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);
        }
         }) {
        @OverrideprotectedMap<String, String> getParams() {

        // Posting parameters to verfication urlMap<String, String> params = newHashMap<String, String>();
        params.put("plate_no", plate_no);
        return params;
       }
    };
//        // Adding request to request queueAppController.getInstance().addToRequestQueue(strReq,tag_string_req);
   }   

Post a Comment for "How To Parse Multiple Rows With Jsonoject"