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

Android应用首页集成Facebook登录及MySQL数据同步技术求助

Hey there! Let's break down how to get your Facebook Login working and sync that user data to your MySQL database step by step. I'll walk you through each part clearly so you understand the logic behind it.

Step-by-Step Guide to Integrate Facebook Login & Sync User Data to MySQL

First, let's fix the Facebook Login implementation, then handle the data sync to your MySQL database.

1. Complete Facebook Login Setup in Android

1.1 Project Dependencies & Manifest

Make sure you have these in your build.gradle (Module level):

implementation 'com.facebook.android:facebook-login:[latest-version]'

And add these entries to your AndroidManifest.xml:

<meta-data
    android:name="com.facebook.sdk.ApplicationId"
    android:value="@string/facebook_app_id"/>

<activity
    android:name="com.facebook.FacebookActivity"
    android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
    android:label="@string/app_name" />
<activity
    android:name="com.facebook.CustomTabActivity"
    android:exported="true">
    <intent-filter>
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />
        <data android:scheme="@string/fb_login_protocol_scheme" />
    </intent-filter>
</activity>

Don't forget to add facebook_app_id and fb_login_protocol_scheme in strings.xml (you'll get these values from your Facebook Developer Dashboard).

1.2 Implement Login Callback in Your Activity

Here's a complete, commented example of your login activity code to replace your partial snippet:

package com.example.anto.loginapp;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Toast;

import com.facebook.AccessToken;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;

import org.json.JSONException;
import org.json.JSONObject;

public class LoginActivity extends AppCompatActivity {

    private static final String TAG = "FacebookLogin";
    private CallbackManager callbackManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        // Initialize CallbackManager to handle login results from Facebook
        callbackManager = CallbackManager.Factory.create();

        LoginButton loginButton = findViewById(R.id.login_button);
        // Request permissions for the data you need (email + public profile is common)
        loginButton.setPermissions("email", "public_profile");

        // Register a callback to handle login success/cancel/error
        loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
            @Override
            public void onSuccess(LoginResult loginResult) {
                Log.d(TAG, "Login successful!");
                // Get the access token to fetch user data via Graph API
                AccessToken accessToken = loginResult.getAccessToken();
                fetchFacebookUserData(accessToken);
            }

            @Override
            public void onCancel() {
                Toast.makeText(LoginActivity.this, "Login cancelled", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onError(FacebookException error) {
                Log.e(TAG, "Login error: " + error.getMessage());
                Toast.makeText(LoginActivity.this, "Login failed: " + error.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    // Fetch user details using Facebook's Graph API
    private void fetchFacebookUserData(AccessToken accessToken) {
        GraphRequest request = GraphRequest.newMeRequest(
                accessToken,
                new GraphRequest.GraphJSONObjectCallback() {
                    @Override
                    public void onCompleted(JSONObject object, GraphResponse response) {
                        try {
                            // Extract user data from the JSON response
                            String facebookId = object.getString("id");
                            String fullName = object.getString("name");
                            String email = object.optString("email", "No email provided");
                            String profilePicUrl = "https://graph.facebook.com/" + facebookId + "/picture?type=large";

                            // Now sync this data to your MySQL database
                            syncUserDataToMySQL(facebookId, fullName, email, profilePicUrl);

                        } catch (JSONException e) {
                            Log.e(TAG, "Error parsing user data: " + e.getMessage());
                        }
                    }
                });

        // Specify exactly which fields you want to retrieve (only ask for what you need!)
        Bundle parameters = new Bundle();
        parameters.putString("fields", "id,name,email");
        request.setParameters(parameters);
        request.executeAsync();
    }

    // Sync user data to MySQL via your backend API (never connect directly from Android!)
    private void syncUserDataToMySQL(String facebookId, String name, String email, String profilePicUrl) {
        // Use an HTTP client like Volley or Retrofit to send data to your server
        // Example using Volley (add Volley dependency first if you haven't):
        String backendUrl = "https://your-server-domain.com/sync-user.php"; // Replace with your actual endpoint

        // Create a JSON body with user data
        JSONObject postData = new JSONObject();
        try {
            postData.put("facebook_id", facebookId);
            postData.put("name", name);
            postData.put("email", email);
            postData.put("profile_pic", profilePicUrl);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        // Implement the Volley POST request here (handle success/failure callbacks)
        Toast.makeText(LoginActivity.this, "Syncing user data...", Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // Pass the login result back to Facebook's CallbackManager
        callbackManager.onActivityResult(requestCode, resultCode, data);
    }
}

2. Backend Setup for MySQL Sync

Android apps can't directly connect to MySQL (it's insecure and violates best practices). You need a server-side script (like PHP, Node.js) that acts as a middleman to receive the data and insert/update it in your database.

Example PHP Script (sync-user.php)

<?php
// Database configuration (replace with your actual credentials)
$host = 'localhost';
$dbname = 'your_database_name';
$username = 'your_db_username';
$password = 'your_db_password';

try {
    // Connect to MySQL using PDO (secure and modern approach)
    $pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // Get the JSON data sent from Android
    $data = json_decode(file_get_contents('php://input'), true);
    $facebookId = $data['facebook_id'];
    $name = $data['name'];
    $email = $data['email'];
    $profilePic = $data['profile_pic'];

    // Check if the user already exists in the database
    $checkStmt = $pdo->prepare("SELECT id FROM users WHERE facebook_id = ?");
    $checkStmt->execute([$facebookId]);
    $existingUser = $checkStmt->fetch();

    if ($existingUser) {
        // Update existing user's details
        $updateStmt = $pdo->prepare("UPDATE users SET name = ?, email = ?, profile_pic = ? WHERE facebook_id = ?");
        $updateStmt->execute([$name, $email, $profilePic, $facebookId]);
        echo json_encode(['status' => 'success', 'message' => 'User profile updated']);
    } else {
        // Insert new user into the database
        $insertStmt = $pdo->prepare("INSERT INTO users (facebook_id, name, email, profile_pic) VALUES (?, ?, ?, ?)");
        $insertStmt->execute([$facebookId, $name, $email, $profilePic]);
        echo json_encode(['status' => 'success', 'message' => 'New user created']);
    }
} catch(PDOException $e) {
    // Return error message if something goes wrong
    echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
}
?>

Key Concepts to Grasp

  • CallbackManager: This handles the login result sent back from Facebook's activity. You must pass onActivityResult to it, otherwise the login success won't trigger.
  • Graph API: Facebook's way to fetch user data after login. The fields parameter lets you request only the data you need (don't ask for unnecessary permissions!).
  • Backend Middleman: Direct MySQL connections from Android are a huge security risk (you'd expose your database credentials). Always use a server-side script to handle database operations.

If you're stuck on specific parts (like setting up Volley/Retrofit, or configuring the Facebook Developer Dashboard), just let me know and I can dive deeper into those details!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:16:51