【发布时间】:2015-11-23 18:17:07
【问题描述】:
我创建了一个应用程序,它使用 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 活动中使用 $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);
我错了吗?谢谢!
【问题讨论】:
-
日志中的
System.out.println(response.toString());行有什么内容? -
在行日志
println返回id。但是为什么Toast不起作用?你认为我需要将JSONObject转换为字符串吗? -
显示来自
System.out.println(response.toString());的字符串 -
这就是我得到的:
I/System.out: 111。是 id 需要的确切 id。 -
111不是有效的 json 字符串,因此无需将 String 转换为 JSONObject 只需使用Toast.makeText(getApplicationContext(), response.toString(), Toast.LENGTH_LONG).show();
标签: java android mysql json android-activity