您好我已经使用android volley编写了一个请求,将String值的ArrayList发送到PhP服务器。服务器需要解码JsonObject(即和ArrayList)并使用MySQL命令查询数据库并返回与ArrayList中任何值相关的结果。
这是我的android请求代码(将ArrayList eventIDBeacon发送到PhP服务器)
private void getEventDetailRespond(RequestQueue requestQueue) {
JSONObject params = new JSONObject();
try {
params.put(Config.EVENT_ID, eventIDBeacon);
} catch (JSONException e) {
e.printStackTrace();
}
//Creating a JSONObject request
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,Config.DATA_URL,params,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject respond) {
try {
eventArray = new JSONArray();
eventDetail = new ArrayList<>();
eventArray = respond.getJSONArray("result");
eventDetail = getEventDetail(eventArray);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(Beacon_MainActivity.this, "Unable to fetch data: " +error.getMessage(),Toast.LENGTH_LONG).show();
}
}
);
//Adding request to the queue
requestQueue.add(jsonObjectRequest);
}
private ArrayList getEventDetail(JSONArray j) {
ArrayList event = new ArrayList();
//Traversing through all the items in the json array
for (int i = 0; i < j.length(); i++) {
try {
//Getting json object
JSONObject json = j.getJSONObject(i);
//Adding the name of the event to array list
event.add(json.getString(Config.EVENT_TITLE));
} catch (JSONException e) {
e.printStackTrace();
}
}
spinner.setAdapter(new ArrayAdapter<String>(Beacon_MainActivity.this, android.R.layout.simple_spinner_dropdown_item, event));
return event;
}
这是我的PhP服务器代码,用于接收数组并使用MySQL命令返回响应
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
// decoding the json array
$post = json_decode(file_get_contents("php://input"), true);
$eventID = $post['EventID'];
require_once('dbconnect.php');
$sql = "SELECT EventID, EventTitle, EventDesc, EventTime FROM Event WHERE EVENTID IN $eventID";
$res = mysqli_query($con,$sql);
$result = array();
while ($row = mysqli_fetch_array($res)){
array_push($result,array(
'EventID'=>$row['EventID'],
'EventTitle'=>$row['EventTitle'],
'EventDesc'=>$row['EventDesc'],
'EventTime'=>$row['EventTime']
));
}
header('Content-Type: application/json');
echo json_encode(array('result'=>$result), 256);
mysqli_close($con);
}
我不知道为什么我没有得到任何结果。任何帮助都非常感谢(我已尝试手动将PhP代码中的$ eventID更改为实际值,并且可以将结果发回)