我正在使用 Volley 编写一个简单的 Android 应用程序。我想知道如何通过 ID 从 MySQL 数据库中选择名字和姓氏,哪个用户在应用程序中输入 editText。这是我的 PHP 脚本:
<?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);
?>
如果我在代码中指定了 ID,它会返回一个 JSON 格式的数据,这是我需要的,所以脚本和数据库都没有问题。我对 $id=1 得到的响应是:
{"users":[{"firstName":"Jonash","lastName":"Corvin"}]}
这是我的 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);
不幸的是,它没有做任何事情......它甚至没有显示任何错误或提示消息。你知道怎么解决吗?
最佳答案
{"users":[{"firstName":"Jonash","lastName":"Corvin"}]}
根据给定的JSON,你需要像这样解析JSON:
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");
关于java - 安卓 Volley : select data from MySQL database by id specified by user,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43815378/