douchi1945 2017-02-02 13:57
浏览 90
已采纳

Android:尝试从服务器检索数据时捕获到JSONException

I'm now writing a code to retrieve JSON array from server. For the Android-side, I'm using OkHttp3 API and here's the part of my code.

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String strResponse = response.body().string();
                Log.i(TAG, strResponse);
                try {
                    JSONObject jsonObject = new JSONObject(strResponse);
                    boolean error = jsonObject.getBoolean("error");

                    if(!error) {
                        String uid = jsonObject.getString("uid");
                        JSONArray people = jsonObject.getJSONArray("users");
                        final String name = people.getJSONObject(0).getString("name");

                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(MainActivity.this, "it works! " + name, Toast.LENGTH_SHORT).show();
                            }
                        });
                    } else {
                        final String strError = jsonObject.getString("error_msg");
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(getApplicationContext(), strError, Toast.LENGTH_SHORT).show();
                            }
                        });
                        hideDialog();
                    }
                } catch (final JSONException e) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Log.i(TAG, "JSONException caught: " + e.getMessage());
                            Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    });
                } finally {
                    hideDialog();
                }
            }
        });

And this is the PHP file which the above code is connected to.

<?php

// when you get a post request with a name called 'search_name'
if(isset($_POST['search_name'])) {

    // get the name value
    $search_name = $_POST['search_name'];

    require_once 'include/db_connect.php';
    $db = new DB_Connect();
    $conn = $db->connect();

    $users = array("error" => FALSE);
    $stmt = $conn->prepare("SELECT unique_id, name, email from users where name LIKE '%$search_name%'");
    $stmt->bind_param("ss", $name, $email);
    $stmt->execute();
    $stmt->store_result();

    // if user with the queried name exists
    if($stmt->num_rows > 0) {
        while($row = mysqli_fetch_array($stmt, MYSQL_ASSOC)) {
            $row_array["uid"] = $row["unique_id"];
            $row_array["users"]["name"] = $row['name'];
            $row_array["users"]["email"] = $row['email'];
            array_push($users, $row_array);
        }
        echo json_encode($users);
    } else {
        $stmt->close();
        $response["error"] = TRUE;
        $response["error_msg"] = "No matching users found.";
        echo json_encode($response);
    }
} 

// if the post request is not what this file is supposed to work with
else {
    $response["error"] = TRUE;
    $response["error_msg"] = "An error occurred while processing your request. Please try again later.";
    echo json_encode($response);
}
?>

So, as I mentioned above already, I want to retrieve an array of names and emails from the MySQL database. In order to do that, I send a POST request to the PHP URL, and then the PHP file processes the statement to retrieve the data which meet the condition, puts them into the array, encodes the array into JSON and echoes that.

Then the Android side's onResponse() method above receives the response and takes the next step. This is what I have done so far, but I'm now stuck.

The process now ends up catching the JSONException. Can somebody help me find out the reason?

Added

Here's the Log with the strResponse.

02-02 23:14:26.203 20668-24366/com.marshall.authentication I/MainActivity:

    <b>Warning</b>:  mysqli_stmt::bind_param(): Number of variables doesn't match number of parameters in prepared statement in <b>/storage/h3/859/644859/public_html/searchfriends.php</b> on line <b>15</b><br />
                                                                           {"error":true,"error_msg":"No matching users found."}
02-02 23:14:26.203 20668-20668/com.marshall.authentication I/MainActivity: JSONException caught: Value <br of type java.lang.String cannot be converted to JSONObject

According to the Log, I'm now starting to believe that the problem is due to the wrong parameters in the bind_param() function in the PHP file. How should I fix it then?

  • 写回答

1条回答 默认 最新

  • duanjian7343 2017-02-02 14:07
    关注

    Try this

    $stmt = $conn->prepare("SELECT unique_id, name, email from users where name LIKE :name");
    $stmt->bind_param(":name", '%' . str_replace('%', '\%', $name) . '%', PDO::PARAM_STR);
    

    In case you want to check if the data from the database is what you expect. Dump it:

    var_dump($response);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置