douchi1945 2017-02-02 05: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 06: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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部