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 yolov8边框坐标
  • ¥15 matlab中使用gurobi时报错
  • ¥15 WPF 大屏看板表格背景图片设置
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真