Android Studio+Java入门者求助:实现登录验证APP连接数据库
Hey there! Since you’ve already wrapped up the PHP backend part, let’s break down exactly how to build the Android side of your login validation feature. I’ll keep this simple and actionable, perfect for someone who knows basic Java/Android but is new to putting a full app together.
First, create a new Empty Activity project in Android Studio. Then we’ll add the libraries needed to handle network requests and data parsing:
- Open your Module-level
build.gradlefile and add these dependencies:dependencies { // OkHttp for reliable network calls implementation 'com.squareup.okhttp3:okhttp:4.10.0' // Gson for easy JSON parsing (in case your PHP returns JSON) implementation 'com.google.code.gson:gson:2.10.1' } - Add internet permission to your
AndroidManifest.xml(required to send requests to your local PHP server):<uses-permission android:name="android.permission.INTERNET" /> - For Android 9+, cleartext HTTP requests are blocked by default. To enable this for local testing, add this line inside the
<application>tag inAndroidManifest.xml:android:usesCleartextTraffic="true"
Create a simple layout for your login screen (activity_login.xml) with fields for username, password, a login button, and a text view to show results:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="16dp" android:gravity="center"> <EditText android:id="@+id/et_username" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Enter Username" android:inputType="text"/> <EditText android:id="@+id/et_password" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Enter Password" android:inputType="textPassword" android:layout_marginTop="16dp"/> <Button android:id="@+id/btn_login" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Login" android:layout_marginTop="24dp"/> <TextView android:id="@+id/tv_result" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="24dp" android:textSize="18sp"/> </LinearLayout>
In your LoginActivity.java, we’ll write code to collect user input, send it to your PHP script, and display the result. Note: We’ll use OkHttp’s async calls to avoid blocking the main thread (Android doesn’t allow network operations on the main thread!).
import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import okhttp3.MediaType; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; import java.io.IOException; public class LoginActivity extends AppCompatActivity { private EditText etUsername, etPassword; private TextView tvResult; private Button btnLogin; // Replace this with your local computer's LAN IP and PHP script path // Example: http://192.168.1.105/login.php private static final String LOGIN_URL = "http://YOUR_COMPUTER_LAN_IP/login.php"; public static final MediaType JSON = MediaType.get("application/json; charset=utf-8"); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); // Link UI elements to code etUsername = findViewById(R.id.et_username); etPassword = findViewById(R.id.et_password); tvResult = findViewById(R.id.tv_result); btnLogin = findViewById(R.id.btn_login); // Set click listener for login button btnLogin.setOnClickListener(v -> attemptLogin()); } private void attemptLogin() { String username = etUsername.getText().toString().trim(); String password = etPassword.getText().toString().trim(); // Basic input validation if (username.isEmpty() || password.isEmpty()) { tvResult.setText("Please fill in all fields!"); return; } // Build JSON request body to send to PHP String jsonBody = "{\"logins\":\"" + username + "\",\"passwords\":\"" + password + "\"}"; RequestBody requestBody = RequestBody.create(jsonBody, JSON); // Create OkHttp client and request OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url(LOGIN_URL) .post(requestBody) .build(); // Execute request asynchronously client.newCall(request).enqueue(new okhttp3.Callback() { @Override public void onFailure(okhttp3.Call call, IOException e) { // Handle network errors (run on main thread to update UI) runOnUiThread(() -> tvResult.setText("Network Error: " + e.getMessage())); } @Override public void onResponse(okhttp3.Call call, Response response) throws IOException { if (response.isSuccessful()) { String serverResponse = response.body().string(); // Update UI with result (must run on main thread) runOnUiThread(() -> { if (serverResponse.equals("success")) { tvResult.setText("Login Successful! 🎉"); } else { tvResult.setText("Login Failed: Invalid credentials"); } }); } else { runOnUiThread(() -> tvResult.setText("Server Error: " + response.code())); } } }); } }
Since you’ve already built the PHP part, just confirm these key points to ensure it works with the Android app:
- Your PHP script accepts POST requests with JSON data (using
file_get_contents('php://input')to read the body) - You use prepared statements to query your database (to avoid SQL injection—never concatenate user input directly into SQL queries!)
- It returns plain text "success" or "failure" (matches what the Android code expects)
Here’s a quick PHP snippet reference in case you need to adjust:
<?php // Enable CORS for local testing header("Access-Control-Allow-Origin: *"); header("Content-Type: text/plain"); // Read JSON input $json = file_get_contents('php://input'); $data = json_decode($json, true); $username = $data['logins']; $password = $data['passwords']; // Connect to your local database $conn = new mysqli('localhost', 'DB_USERNAME', 'DB_PASSWORD', 'DB_NAME'); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } // Use prepared statement to prevent SQL injection $stmt = $conn->prepare("SELECT * FROM your_table WHERE logins = ? AND passwords = ?"); $stmt->bind_param("ss", $username, $password); $stmt->execute(); $result = $stmt->get_result(); // Send response echo $result->num_rows > 0 ? "success" : "failure"; // Clean up $stmt->close(); $conn->close(); ?>
- Make sure your Android emulator/physical device is connected to the same Wi-Fi network as your local computer
- Start your local web server (XAMPP/WAMP/MAMP) and confirm your PHP script is accessible via the LAN IP you used in the Android code
- Run the app, enter valid/invalid credentials, and check the result text view
- If you get network errors: Double-check your computer’s LAN IP (use
ipconfigon Windows orifconfigon macOS/Linux) and ensure your web server is running - If server errors occur: Check your PHP error log for issues with database connections or query execution
- If cleartext is blocked: Verify you added
android:usesCleartextTraffic="true"to yourAndroidManifest.xml
内容的提问来源于stack exchange,提问作者Kamil Ciesielski

