You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android Volley登录问题:PHP返回JSON但无法跳转至下一页面

Hey Chandra, let's break down your Volley login issues step by step—sounds like we've got a mix of network, authentication, and response handling problems to fix. Here's how to tackle each one:

1. Fix the "Bad network connection" errors

First, let's rule out basic network and Volley setup issues:

  • Double-check permissions: Make sure your AndroidManifest.xml includes these critical permissions—Volley needs them to access the network and detect connection state:
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    
  • Reuse your RequestQueue: Don't create a new RequestQueue for every login attempt. Initialize it once (in your Application class or Activity's onCreate) and reuse it—this prevents connection leaks and instability:
    RequestQueue queue = Volley.newRequestQueue(this);
    
  • Use a reachable URL: If testing locally, don't use localhost (Android emulators can't reach your computer's localhost directly). Instead, use your computer's local IP address (like 192.168.1.100). Test the URL in a browser or Postman first to confirm it's accessible.
  • Increase timeout limits: Volley's default timeout might be too short for your server. Add a retry policy to give the request more time:
    StringRequest loginRequest = new StringRequest(Request.Method.POST, LOGIN_URL,
            response -> { /* Handle success */ },
            error -> { /* Handle error */ }) {
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            Map<String, String> params = new HashMap<>();
            params.put("email", yourEmailInput.getText().toString().trim());
            params.put("password", yourPasswordInput.getText().toString().trim());
            return params;
        }
    };
    
    loginRequest.setRetryPolicy(new DefaultRetryPolicy(
            5000, // 5-second timeout
            DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    queue.add(loginRequest);
    
2. Fix the "passwords don't match" false positives

This almost always boils down to mismatched password handling between your Android app and PHP backend. Let's fix your PHP logic first:

  • Use password_verify for hashed passwords: If you stored passwords in the database using password_hash() (which you absolutely should for security), you can't compare the raw input password directly to the stored hash. Use password_verify() instead:
    <?php
    include("Connection.php");
    header('Content-Type: application/json; charset=utf-8'); // Ensure proper JSON encoding
    
    if(isset($_POST["email"]) && isset($_POST["password"])) {
        // Sanitize inputs to prevent SQL injection
        $email = mysqli_real_escape_string($conn, $_POST["email"]);
        $inputPassword = $_POST["password"];
    
        $result = mysqli_query($conn, "SELECT password FROM users WHERE email = '$email'");
        if(mysqli_num_rows($result) > 0) {
            $user = mysqli_fetch_assoc($result);
            // Verify the password against the stored hash
            if(password_verify($inputPassword, $user['password'])) {
                echo json_encode(["status" => "success", "message" => "Login successful"]);
            } else {
                echo json_encode(["status" => "error", "message" => "passwords don't match"]);
            }
        } else {
            echo json_encode(["status" => "error", "message" => "User not found"]);
        }
    } else {
        echo json_encode(["status" => "error", "message" => "Missing email or password"]);
    }
    mysqli_close($conn);
    ?>
    
  • Check parameter spelling: Make sure the keys in your Volley getParams() match exactly what your PHP expects ("email" and "password"—no typos like "passwd" or "Email").
  • Trim input values: Add .trim() to your Android input fields to avoid accidental whitespace causing mismatches (e.g., a space at the end of the password).
3. Fix the post-login page not redirecting

This is usually a problem with how you're parsing the server's JSON response or executing the navigation:

  • Properly parse the JSON response: Volley's success callback runs on the main thread, but you need to correctly parse the JSON to trigger the redirect:
    response -> {
        try {
            JSONObject responseJson = new JSONObject(response);
            String status = responseJson.getString("status");
            if("success".equals(status)) {
                // Navigate to the next activity
                Intent homeIntent = new Intent(LoginActivity.this, HomeActivity.class);
                startActivity(homeIntent);
                finish(); // Close the login activity so users can't go back
            } else {
                String errorMsg = responseJson.getString("message");
                Toast.makeText(LoginActivity.this, errorMsg, Toast.LENGTH_SHORT).show();
            }
        } catch (JSONException e) {
            e.printStackTrace();
            Toast.makeText(LoginActivity.this, "Invalid server response", Toast.LENGTH_SHORT).show();
        }
    }
    
  • Ensure no extra output in PHP: If your Connection.php or login.php has extra whitespace, newlines, or echo statements outside the JSON response, it will break JSON parsing. Add ob_start(); at the top of your PHP files and ob_end_clean(); before echoing the JSON to eliminate extra output.
  • Debug with logs: Print the full server response in Android to see what's actually coming back:
    Log.d("LoginResponse", "Raw response: " + response);
    
    This will help you spot if the JSON is malformed or if the status isn't what you expect.
Quick Debugging Tip

Before blaming Volley, test your PHP endpoint with Postman or curl. Send a POST request with valid email/password and check if the JSON response is correct. If it works there, the problem is definitely in your Android code.

内容的提问来源于stack exchange,提问作者Chandra Kiran

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 12:20:15