基于Firebase Auth获取用户ID生成二维码的代码修改需求
Got it, let's walk through how to modify your QR code generator to pull the current user's UID from Firebase Authentication and use that for the QR code. Here's a step-by-step solution with optional optimizations to make the flow smoother:
Step 1: Confirm Firebase Auth Setup
First, make sure your project already has Firebase Authentication configured (with dependencies added in build.gradle and login flow working). If not, you'll need to finish that first, but I'll assume you've got that covered since you're asking about fetching the UID.
Step 2: Modify CodeQR.java (Core Logic Changes)
We'll update the Activity to fetch the UID on startup, populate the EditText, add error handling for unauthenticated users, and streamline the QR generation flow:
public class CodeQR extends AppCompatActivity { EditText User_txt; Button generateBtn; ImageView qrImage; private String currentUserUid; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_code_q_r); User_txt = findViewById(R.id.user_id); generateBtn = findViewById(R.id.generate_btn); qrImage = findViewById(R.id.imageview); // Fetch current logged-in user's UID FirebaseUser currentUser = FirebaseAuth.getInstance().getCurrentUser(); if (currentUser != null) { currentUserUid = currentUser.getUid(); // Populate EditText and lock it to prevent user edits User_txt.setText(currentUserUid); User_txt.setEnabled(false); User_txt.setHint("Your UserID (auto-filled)"); } else { // Handle case where no user is logged in User_txt.setHint("No user logged in"); generateBtn.setEnabled(false); Toast.makeText(this, "Please log in first to generate your QR code", Toast.LENGTH_SHORT).show(); } generateBtn.setOnClickListener(view -> { // Use the pre-fetched UID directly (more reliable than reading EditText) if (currentUserUid == null || currentUserUid.isEmpty()) { Toast.makeText(CodeQR.this, "No valid UserID found", Toast.LENGTH_SHORT).show(); return; } try { MultiFormatWriter multiFormatWriter = new MultiFormatWriter(); BitMatrix bitMatrix = multiFormatWriter.encode(currentUserUid, BarcodeFormat.QR_CODE, 500, 500); BarcodeEncoder barcodeEncoder = new BarcodeEncoder(); Bitmap bitmap = barcodeEncoder.createBitmap(bitMatrix); qrImage.setImageBitmap(bitmap); } catch (Exception e) { e.printStackTrace(); Toast.makeText(CodeQR.this, "Failed to generate QR code", Toast.LENGTH_SHORT).show(); } }); } }
Key Changes Breakdown:
- Added
currentUserUidto store the fetched UID for reuse - Added checks for authenticated users:
- If a user is logged in: auto-fill the EditText and disable editing to avoid accidental changes
- If no user is logged in: disable the generate button and show a helpful toast
- Modified the generate button logic to use the pre-fetched UID directly (avoids relying on EditText input, even if it's disabled)
- Added user-friendly error toasts for edge cases
Step 3: Tweak the Layout (CodeQR.xml)
Since we're auto-filling and locking the EditText, update the layout to reflect this for better user clarity:
<EditText android:id="@+id/user_id" android:layout_width="match_parent" android:layout_height="104dp" android:hint="Your UserID (auto-filled)" android:enabled="false" android:background="@android:drawable/edit_text_disabled" <!-- Optional visual cue for disabled state --> app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="1.0" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_bias="0.287" />
Optional Optimizations for Better UX
- Skip the EditText entirely: If you don't need to display the UID to users, remove the EditText from the layout and generate the QR code directly using the UID. This simplifies the UI.
- Auto-generate QR on startup: After fetching the UID, call the QR generation code immediately instead of waiting for the user to click the button. This saves a step for users.
- Listen for auth state changes: Add an
AuthStateListenerto update the UI in real-time if the user logs in/out while the Activity is active:
private FirebaseAuth.AuthStateListener authStateListener; @Override protected void onStart() { super.onStart(); authStateListener = firebaseAuth -> { FirebaseUser user = firebaseAuth.getCurrentUser(); if (user != null) { currentUserUid = user.getUid(); User_txt.setText(currentUserUid); generateBtn.setEnabled(true); // Auto-generate QR here if you want } else { User_txt.setText(""); User_txt.setHint("No user logged in"); generateBtn.setEnabled(false); qrImage.setImageBitmap(null); // Clear existing QR code Toast.makeText(this, "Please log in first", Toast.LENGTH_SHORT).show(); } }; FirebaseAuth.getInstance().addAuthStateListener(authStateListener); } @Override protected void onStop() { super.onStop(); if (authStateListener != null) { FirebaseAuth.getInstance().removeAuthStateListener(authStateListener); } }
内容的提问来源于stack exchange,提问作者Hannah OC

