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

Android Volley+PHP+MySQL(XAMPP)下JSONException及登录问题求助

Hey there, let's break down your issues step by step—both the connection timeout and JSONException are common pitfalls when working with Volley + PHP/MySQL, so we'll tackle them one by one.

1. Fixing the Connection Timeout Issue

First, let's eliminate the network-related problems:

  • Check Android Permissions: Make sure your AndroidManifest.xml includes these critical permissions (Volley won't work without them):
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    
  • Use Local Network IP Instead of localhost: When testing with XAMPP, localhost on your Android device points to the device itself, not your computer's server. Replace localhost in your Volley URL with your computer's local IP (e.g., 192.168.1.105—find this in your XAMPP network settings or OS network info).
  • Adjust Volley Timeout Settings: The default timeout might be too short for local testing. Extend it in your request:
    StringRequest loginRequest = new StringRequest(/* ... */);
    loginRequest.setRetryPolicy(new DefaultRetryPolicy(
            5000, // 5-second timeout
            DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT
    ));
    
2. Resolving the JSONException (String → JSONObject)

This error almost always means your server isn't returning valid JSON. Let's fix your PHP code first, since that's the root cause here:

Fix Your Login.php Code

From your snippet, I see two big issues:

  1. You used & instead of AND in your SQL condition (invalid syntax that breaks the query)
  2. You're not properly formatting the response as JSON

Here's a corrected, secure version of your PHP:

<?php
include("Connection.php");
$response = []; // Initialize a standard response array

// Validate input parameters
if(isset($_POST["email"]) && isset($_POST["password"])) {
    // Sanitize inputs to prevent SQL injection
    $email = mysqli_real_escape_string($conn, $_POST["email"]);
    $password = mysqli_real_escape_string($conn, $_POST["password"]);

    // Fix SQL condition: use AND instead of &
    $result = mysqli_query($conn, "SELECT * FROM user_master WHERE email='$email' AND password='$password'");

    if(mysqli_num_rows($result) > 0) {
        $user = mysqli_fetch_assoc($result);
        $response["success"] = 1;
        $response["message"] = "Login successful";
        $response["user"] = $user;
    } else {
        $response["success"] = 0;
        $response["message"] = "Invalid email or password";
    }
} else {
    $response["success"] = 0;
    $response["message"] = "Missing email or password parameters";
}

// Set correct content type and output valid JSON
header('Content-Type: application/json');
echo json_encode($response);
mysqli_close($conn);
?>

Adjust Your Volley Response Handling

Add debug logging to verify what the server returns, then safely parse the JSON:

StringRequest loginRequest = new StringRequest(Request.Method.POST, LOGIN_URL,
        response -> {
            // Debug: Print the raw server response to check validity
            Log.d("LoginDebug", "Server Response: " + response);
            try {
                JSONObject jsonResponse = new JSONObject(response);
                int success = jsonResponse.getInt("success");
                if(success == 1) {
                    // Handle successful login
                    Toast.makeText(getApplicationContext(), jsonResponse.getString("message"), Toast.LENGTH_SHORT).show();
                } else {
                    // Handle failed login
                    Toast.makeText(getApplicationContext(), jsonResponse.getString("message"), Toast.LENGTH_SHORT).show();
                }
            } catch (JSONException e) {
                e.printStackTrace();
                Toast.makeText(getApplicationContext(), "Invalid server response: " + e.getMessage(), Toast.LENGTH_SHORT).show();
            }
        },
        error -> Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show()
) {
    @Override
    protected Map<String, String> getParams() {
        Map<String, String> params = new HashMap<>();
        params.put("email", emailEditText.getText().toString().trim());
        params.put("password", passwordEditText.getText().toString().trim());
        return params;
    }
};

// Add request to Volley queue
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
queue.add(loginRequest);
3. Quick Debug Checks
  • Test your Login.php directly with Postman or a browser (send a POST request with email and password parameters). If it returns HTML error text instead of JSON, fix the PHP first.
  • Verify XAMPP's Apache and MySQL services are running, and your user_master table exists in phpMyAdmin with the correct columns.

内容的提问来源于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 11:40:41