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

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.

Step 1: Prep Your Android Project

First, create a new Empty Activity project in Android Studio. Then we’ll add the libraries needed to handle network requests and data parsing:

  1. Open your Module-level build.gradle file 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'
    }
    
  2. Add internet permission to your AndroidManifest.xml (required to send requests to your local PHP server):
    <uses-permission android:name="android.permission.INTERNET" />
    
  3. For Android 9+, cleartext HTTP requests are blocked by default. To enable this for local testing, add this line inside the <application> tag in AndroidManifest.xml:
    android:usesCleartextTraffic="true"
    
Step 2: Build the Login UI

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>
Step 3: Handle Login Logic & Network Requests

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()));
                }
            }
        });
    }
}
Step 4: Double-Check Your PHP Backend

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();
?>
Step 5: Test the App
  1. Make sure your Android emulator/physical device is connected to the same Wi-Fi network as your local computer
  2. 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
  3. Run the app, enter valid/invalid credentials, and check the result text view
Troubleshooting Tips
  • If you get network errors: Double-check your computer’s LAN IP (use ipconfig on Windows or ifconfig on 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 your AndroidManifest.xml

内容的提问来源于stack exchange,提问作者Kamil Ciesielski

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 09:14:48