使用连接到php的volley来获取jsonobject响应

时间:2015-12-22 23:54:43

标签: php android android-volley

    public void volley(){
    String url = "http://percyteng.com/get_users_details.php";

    StringRequest postRequest = new StringRequest(Request.Method.POST, url,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {
                        JSONObject jsonResponse = new JSONObject(response).getJSONObject("user");
                        String useremail = jsonResponse.getString("useremail"),
                                password = jsonResponse.getString("password");
                        alert(useremail,password);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    error.printStackTrace();
                }
            }
    ) {
        @Override
        protected Map<String, String> getParams()
        {
            Map<String, String>  params = new HashMap<>();
            // the POST parameters:
            params.put("useremail", etUsername.getText().toString());
            params.put("password", etPassword.getText().toString());
            return params;
        }
    };
    Volley.newRequestQueue(this).add(postRequest);

这是凌空连接代码,我在我的android java登录类中。我使用警报进行测试,发现这条线路并没有真正起作用 JSONObject jsonResponse = new JSONObject(response).getJSONObject("user"); 网址应该是正确的,下面是我的PHP代码。

`$response = array();`

// include db connect class
require_once __DIR__ . '/db_connect.php';
try{
    // connecting to db

    $con = new DB_CONNECT();

    $db = $con->connect();
    echo $_POST["useremail"];
    // check for post data

    if (isset($_POST["useremail"]) && isset($_POST["password"])) {
        $email = $_POST["useremail"];
        $password = $_POST["password"];
            // $useremail = "percytsy@gmail.com";
            // $password= "coolpig123";
            // echo "shit";
        // get a product from products table using PDO prepared statement
        $result = $db->prepare("SELECT * FROM user WHERE useremail = :useremail AND password = :password");
        echo "shit";
        $result->bindParam(":useremail", $useremail, PDO::PARAM_STR, 30);
        $result->bindParam(":password", $password, PDO::PARAM_STR, 25); 

        // bind the values individually
        //execute will execute db command with binded variables. Becaise we
        // binded first, the parameters for eceute() can be empty
        $result->execute();
        if (!empty($result)) {
            // check for empty result
            if ($result->rowCount() > 0) {
                $result = $result->fetch();
                $user = array();
                $user["useremail"] = $result["useremail"];
                $user["password"] = $result["password"];
                // success
                $response["success"] = 1;
                // user node
                $response["user"] = array();
                array_push($response["user"], $user);
                // echoing JSON response
                echo json_encode($response);

            } else {
                // no product found
                $response["success"] = 0;
                $response["message"] = "No user found";
                // echo no users JSON
                echo json_encode($response);
            }
        } else {
            // no product found
            $response["success"] = 0;
            $response["message"] = "Empty result";
            // echo no users JSON
            echo json_encode($response);
        }
    } else {
        // required field is missing
        $response["success"] = 0;
        $response["message"] = "Required field(s) is missing";
        // echoing JSON response
        echo json_encode($response);
    }
} catch(PDOException $e){
    print "Sorry, a database error occurred. Please try again later.\n";
    print $e->getMessage();
}
?>

我之前通过输入参数测试了php代码,并成功连接到我服务器上的mysql。所以我想我的PHP代码应该没有问题。

另外,对问题的另一个猜测是我没有在我的服务器中为android和php连接做一些必要的sudo apt-get ....因为此问题事先发生。但是,我不知道到底需要安装什么。

1 个答案:

答案 0 :(得分:0)

您需要在传递请求之前调用以下代码来启动您的Volley:

// Instantiate the cache
Cache cache = new DiskBasedCache(mContext.getCacheDir(), 1024 * 1024); // 1MB cap
// Set up the network to use HttpURLConnection as the HTTP client.
Network network = new BasicNetwork(new HurlStack());
// Instantiate the RequestQueue with the cache and network.
mRequestQueue = new RequestQueue(cache, network);
// Start the queue
mRequestQueue.start();
// Add request to queue
mRequestQueue.add(postRequest)