我创建了一个使用 Web 服务器上的 mysql 数据库的应用程序。我使用 php 文件插入一些记录,如下所示:
<?php
if($_SERVER["REQUEST_METHOD"]=="POST") {
require 'connection.php';
createUsername();
}
function createUsername() {
global $connect;
$username = $_POST["username"];
$query = " INSERT INTO statistics(username) VALUES ('$username');";
$result = $connect->query($query);
$lastInsertId = $connect->insert_id;
header('Content-Type: application/json');
echo json_encode($lastInsertId);
}
?>
我需要在 Android Activity 中使用 $lastInsertId
变量。我尝试使用“VOLLEY”来做到这一点。这是我的代码:
queue = Volley.newRequestQueue(getApplicationContext());
JsonObjectRequest jsonObjectRequestLastInsertId = new JsonObjectRequest(Request.Method.POST, insertUrl, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
System.out.println(response.toString());
try {
JSONArray ids = response.getJSONArray("lastInsertId");
for (int i = 0; i < ids.length(); i++) {
JSONObject student = ids.getJSONObject(i);
String lastInsertId = student.getString(this);
Toast.makeText(getApplicationContext(), lastInsertId, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
System.out.append(error.getMessage());
}
});
queue.add(jsonObjectRequestLastInsertId);
我错了吗?谢谢!
最佳答案
您仅发送一个号码作为回复。我会发送更多 JSON 风格的内容,如下所示:
echo json_encode(array("lastInsertId" => $lastInsertId));
您假设响应中有一个名为 lastInsertId
的 json 数组:
JSONArray ids = response.getJSONArray("lastInsertId");
上面的代码不正确。 lastInsertId
是 Android 代码中打开数值的键。如果您仍然遇到问题,请在此处发表评论并提供更多详细信息。
关于java - 如何从 php 文件获取变量并在 Android Activity 中使用它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33877801/