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

Android集成Firebase数据库:数据保存后跳转失败及自动ID问题求助

Fixing Your Firebase Android App Issues: Activity Navigation & Custom Database IDs

Hey there! Let's work through the two issues you're hitting with your Firebase-connected Android app. I've been in similar spots before, so let's break this down step by step.


1. Fixing the Registration → Login Activity Navigation Failure

First up, the navigation issue after saving data. Most of the time, this happens because the navigation code isn't running in the right place (outside Firebase's success callback) or there's a small oversight in how you're starting the activity. Here's what to check:

  • Make sure you're triggering navigation inside Firebase's success callback
    If you call startActivity() outside of addOnSuccessListener(), it might run before the data is actually saved (or even if the save fails). Always put the navigation code inside the success handler to ensure it only runs when the data is safely stored.

    Example code snippet:

    // Assume you have a Firebase Database reference
    DatabaseReference userRef = FirebaseDatabase.getInstance().getReference("users");
    
    // Save user data
    userRef.child(yourCustomUserId).setValue(userObject)
        .addOnSuccessListener(new OnSuccessListener<Void>() {
            @Override
            public void onSuccess(Void unused) {
                // This is the RIGHT place to trigger navigation
                Intent intent = new Intent(Registration.this, LoginActivity.class);
                // Optional: Clear the back stack so users can't go back to registration
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                startActivity(intent);
                finish(); // Close the Registration activity
            }
        })
        .addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                // Don't forget to handle failures here (show a toast, log the error)
                Toast.makeText(Registration.this, "Save failed: " + e.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    
  • Verify LoginActivity is registered in AndroidManifest.xml
    Double-check that your LoginActivity is declared in the manifest—if it's missing, the app will crash silently (or throw an exception you might not be catching). Look for this entry:

    <activity
        android:name=".LoginActivity"
        android:exported="true" /> <!-- Set exported to true if it's a launch activity, adjust as needed -->
    
  • Check for uncaught exceptions
    Add a try-catch block around the navigation code (or check Logcat for errors) to see if there's an exception stopping the navigation. For example:

    try {
        Intent intent = new Intent(Registration.this, LoginActivity.class);
        startActivity(intent);
        finish();
    } catch (Exception e) {
        Log.e("Registration", "Navigation failed: " + e.getMessage());
    }
    

2. Preventing Firebase from Generating Auto IDs

Firebase Realtime Database automatically creates unique IDs when you use the push() method. If you want to use your own custom ID instead, you need to explicitly specify the key using child() before calling setValue().

When does Firebase auto-generate IDs?

This happens when you do something like:

// This creates a random auto-generated ID
userRef.push().setValue(userObject);

How to use a custom ID instead:

Choose a unique identifier for your data (like a user's email, phone number, or Firebase Auth UID) and use child() to set that as the key:

// Example 1: Use Firebase Auth UID (best practice for user profiles)
FirebaseUser currentUser = FirebaseAuth.getInstance().getCurrentUser();
if (currentUser != null) {
    String userId = currentUser.getUid();
    userRef.child(userId).setValue(userObject);
}

// Example 2: Use a custom unique ID (like a phone number or username)
String customId = "user_12345"; // Or get this from user input, ensure it's unique
userRef.child(customId).setValue(userObject);

Important Notes:

  • Ensure your custom ID is unique across your database. If you use a non-unique ID, it will overwrite existing data with that key.
  • push() is still useful for collections where you don't need a custom key (like a list of posts, messages, etc.)—it guarantees unique IDs every time.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 03:27:54