0
我還是一個新手,我需要幫助。也許我錯過了一些東西......遇到「org.json.JSONException:java.lang.String類型的值不能轉換爲JSONObject」
這裏是我的PHP代碼
<?php
$con = mysqli_connect("localhost", "root", "", "customer");
$order_name = $_POST["order_name"];
$order_cust = $_POST["order_cust"];
$quantity = $_POST["quantity"];
$statement = mysqli_prepare($con, "INSERT INTO order (order_name, order_cust, quantity) VALUES (?, ?, ?)");
mysqli_stmt_bind_param($statement, "sss", $order_name, $order_cust, $quantity);
mysqli_stmt_execute($statement);
$response = array();
$response["success"] = true;
echo json_encode($response);
?>
,然後這裏是我的響應代碼..
import com.android.volley.Response;
import com.android.volley.toolbox.StringRequest;
import java.util.HashMap;
import java.util.Map;
public class OrderRequest extends StringRequest {
private static final String ORDER_REQUEST_URL = "http://10.0.2.2/customer/Insert.php";
private Map<String, String> params;
public OrderRequest(String order_name, String order_cust, String quantity, Response.Listener<String> listener){
super(Method.POST, ORDER_REQUEST_URL, listener, null);
params = new HashMap<>();
params.put ("order_name", order_name);
params.put ("order_cust", order_cust);
params.put ("quantity", quantity);
}
@Override
public Map<String, String> getParams() {
return params;
}
}
最後,這是我的按鈕活動代碼...
bConfirm.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
final String user_id = etUsername.getText().toString();
final String date = etDate.getText().toString();
final String time = etTime.getText().toString();
final String pax = etPax.getText().toString();
Response.Listener<String> responseListener = new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try{
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if(success){
AlertDialog.Builder builder = new AlertDialog.Builder(ReservationActivity.this);
builder.setMessage("Success! Your reservation has been added to our Queue!").setNegativeButton("Confirm", null).create().show();
}else{
AlertDialog.Builder builder = new AlertDialog.Builder(ReservationActivity.this);
builder.setMessage("Reservation failed or missing credentials...").setNegativeButton("Retry", null).create().show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
ReservationRequest reservationRequest = new ReservationRequest(user_id, date, time, pax, responseListener);
RequestQueue queue = Volley.newRequestQueue(ReservationActivity.this);
queue.add(reservationRequest);
}
});
這是LogCat
W/System.err: org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
我需要幫助pleaseee ...
看來你的PHP代碼返回了一些JSON而不是一些JSON。它爲什麼這樣做? – immibis