Android:尝试从服务器

时间:2017-02-02 13:57:11

标签: php android json

我现在正在编写代码来从服务器检索JSON数组。对于Android方面,我使用的是OkHttp3 API,这是我的代码的一部分。

            @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();
                }
            }
        });

这是上面代码所连接的PHP文件。

<?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);
}
?>

所以,正如我上面提到的,我想从MySQL数据库中检索一组名称和电子邮件。为了做到这一点,我向PHP URL发送一个POST请求,然后PHP文件处理该语句以检索满足条件的数据,将它们放入数组中,将数组编码为JSON并回显它。

然后,Android方面的onResponse()方法接收响应并采取下一步措施。这是我到目前为止所做的,但我现在卡住了。

此过程现在最终会抓住JSONException。有人可以帮我找出原因吗?

点击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

根据Log,我现在开始相信问题是由于PHP文件中bind_param()函数中的错误参数引起的。那我该怎么办呢?

1 个答案:

答案 0 :(得分:0)

试试这个

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

如果您想检查数据库中的数据是否符合您的预期。转储它:

var_dump($response);