java.lang.String类型的值无法转换为JSONObject

时间:2016-11-07 06:29:21

标签: java php android

我在这里苦苦挣扎,我的应用程序中有一个研究按钮,它将调用PHP文件来执行SELECT(并获得几行)。这是我的php文件:

$con = mysqli_connect("***", "***", "***", "***");  
$city = $_POST["city"];  
$statement = mysqli_prepare($con, "SELECT name FROM Restaurants WHERE city = ? ");
mysqli_stmt_bind_param($statement, "s", $city);
mysqli_stmt_execute($statement);

mysqli_stmt_store_result($statement);
mysqli_stmt_bind_result($statement, $city);

$response = array();
$response["success"] = false;  
$i=-1

while(mysqli_stmt_fetch($statement)){
    $response["success"] = true; 
    while($row = mysqli_fetch_array($statement)){
        $i++;

        $response["name"][$i]=$row[$i];
        $response["name"][$i]=$row[$i];

    }       
}
echo json_encode($response);

我从.java文件收到错误。这是我的.java文件中的按钮监听器:

public void bSearchRestaurantClicked(View v) {

    final EditText etCity = (EditText) findViewById(R.id.etSearchRestaurantsCity);
    final String city = etCity.getText().toString();

    Response.Listener<String> responseListener = new Response.Listener<String>() {
        public void onResponse(String response) {
            try {
                JSONObject jsonResponse = new JSONObject(response);
                boolean success = jsonResponse.getBoolean("success");

                if (success) {

                    String nameCities = jsonResponse.getString("name");

                    System.out.println("=======> "+nameCities);

                    Intent intent = new Intent(AreaActivityClient.this, ResultSearchActivity.class);

                    intent.putExtra("city", city);

                    intent.putExtra("cities", nameCities);

                    AreaActivityClient.this.startActivity(intent);

                } else {
                    AlertDialog.Builder builder = new AlertDialog.Builder(AreaActivityClient.this);
                    builder.setMessage("Login Failed !").setNegativeButton("Retry", null).create().show();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    };
    SearchRequest searchRequest = new SearchRequest(city, responseListener);
    RequestQueue queue = Volley.newRequestQueue(AreaActivityClient.this);
    queue.add(searchRequest);

错误在这一行:

                JSONObject jsonResponse = new JSONObject(response);

这是我的SearchRequest.java文件:

private static final String SEARCH_REQUEST_URL="file.php";
private Map<String,String> params;
public SearchRequest(String city, Response.Listener<String> listener){
    super(Request.Method.POST,SEARCH_REQUEST_URL,listener,null);
    params = new HashMap<>();
    params.put("city",city);
}

我很确定错误来自.php文件,但我无法找到它... 提前感谢您的回答。

1 个答案:

答案 0 :(得分:0)

也许你可以

log.v(response);

然后检查响应是一个JSON字符串

从简单到复杂的调试