I’m writing a simple Android application using Volley. I’d like to know how to select a first name and a last name from MySQL database by ID, which user enter into editText in application. This is my PHP script:
<?php include 'connection.php'; global $connect; $id = $_POST["id"]; $query = "SELECT firstName, lastName FROM users WHERE id = '$id'"; $result = mysqli_query($connect, $query); $number_of_rows = mysqli_num_rows($result); $response = array(); if($number_of_rows > 0) { while($row = mysqli_fetch_assoc($result)) { $response[] = $row; } } header('Content-Type: application/json'); echo json_encode(array("users"=>$response)); mysqli_close($connect); ?>
If I specified the ID in the code, it returns a data in JSON, which I demand, so the script and the database are ok. The response which I get for $id=1 is:
{"users":[{"firstName":"Jonash","lastName":"Corvin"}]}
And this is my code of StringRequest:
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() { @Override public void onResponse(String response) { try { JSONArray jsonArray = new JSONArray(response); JSONObject jsonObject = jsonArray.getJSONObject(0); String firstName = jsonObject.getString("firstName"); String lastName = jsonObject.getString("lastName"); firstNameTV.setText(firstName); lastNameTV.setText(lastName); } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Toast.makeText(MainActivity.this, "Something went wrong",Toast.LENGTH_LONG).show(); error.printStackTrace(); } }) { @Override protected Map<String, String> getParams() throws AuthFailureError { Map<String,String> parameters = new HashMap<String, String>(); parameters.put("id", idEditText.getText().toString()); return parameters; } }; queue.add(stringRequest);
Unfortunately, it doesn’t do anything… It even doesn’t show any error or toast message. Do you know how to fix it?
Advertisement
Answer
{“users”:[{“firstName”:”Jonash”,”lastName”:”Corvin”}]}
According to the given JSON you need to parse the JSON like this:
JSONObject jsonobject = new JSONObject(response); JSONArray jsonarray = jsonobject.getJSONArray("users"); JSONObject data = jsonArray.getJSONObject(0); String firstName = data.getString("firstName"); String lastName = data.getString("lastName");