You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Android Kotlin中Firebase Auth结合实时数据库显示用户信息及错误解决

Hey there! Let's tackle your issues one by one—first the Firebase Realtime Database data retrieval problem, then those two compilation errors in your LoginActivity.

1. Fixing User Name & Favorite Color Display from Realtime Database

Since you can already show the user's email after login, your Firebase Authentication flow is working correctly. The issue likely lies in how you're fetching data from the Realtime Database, or in your database structure/rules. Here's how to fix it:

Step 1: Verify Your Database Structure & Rules

First, confirm that when you register a user, you're writing their data to the correct path (usually users/{userUid}). Your registration code should look something like this:

firebaseAuth.createUserWithEmailAndPassword(email, password)
    .addOnCompleteListener(this) { task ->
        if (task.isSuccessful) {
            val currentUser = firebaseAuth.currentUser
            // Create a map with user details
            val userData = hashMapOf(
                "email" to email,
                "name" to userNameInput.text.toString(),
                "favoriteColor" to favoriteColorInput.text.toString()
            )
            // Write to Realtime Database at "users/{uid}"
            FirebaseDatabase.getInstance().getReference("users/${currentUser?.uid}")
                .setValue(userData)
                .addOnSuccessListener {
                    // Navigate to login or main screen
                }
        }
    }

Next, check your Firebase Database rules to ensure authenticated users can read their own data. Update your rules to:

{
  "rules": {
    "users": {
      "$uid": {
        ".read": "$uid === auth.uid",
        ".write": "$uid === auth.uid"
      }
    }
  }
}

Step 2: Fetch & Display Data in MainActivity

In your MainActivity, after login, fetch the user's data from the database using their UID:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    val currentUser = FirebaseAuth.getInstance().currentUser
    currentUser?.let { user ->
        // Show email first (you already have this part)
        emailTextView.text = user.email

        // Fetch user data from Realtime Database
        val userDbRef = FirebaseDatabase.getInstance().getReference("users/${user.uid}")
        userDbRef.addListenerForSingleValueEvent(object : ValueEventListener {
            override fun onDataChange(snapshot: DataSnapshot) {
                if (snapshot.exists()) {
                    // Extract name and favorite color
                    val userName = snapshot.child("name").value.toString()
                    val favoriteColor = snapshot.child("favoriteColor").value.toString()
                    // Update UI
                    userNameTextView.text = userName
                    favoriteColorTextView.text = favoriteColor
                } else {
                    Toast.makeText(this@MainActivity, "User data not found", Toast.LENGTH_SHORT).show()
                }
            }

            override fun onCancelled(error: DatabaseError) {
                Toast.makeText(this@MainActivity, "Failed to load data: ${error.message}", Toast.LENGTH_SHORT).show()
            }
        })
    }
}
2. Fixing LoginActivity Compilation Errors

Let's address those two errors directly:

ERROR 1: Ambiguous Method Overload for putExtra

This happens when Kotlin can't infer which Intent.putExtra() overload to use, usually because you're passing a nullable value or a type that matches multiple overloads.

Fix:

Ensure you're passing a non-null value, or explicitly handle nulls. For example:

// If you're passing a nullable String (like user?.email)
val userEmail = user?.email ?: "No email provided"
intent.putExtra("USER_EMAIL", userEmail)

// Or if you're passing other types, make sure the type matches the overload
// e.g., don't pass an Int where a String is expected

ERROR 2: Unresolved Reference user

This error means the user variable you're trying to use isn't defined in the current scope. Common scenarios:

  • You defined user inside a callback (like addOnCompleteListener) but tried to use it outside that block.
  • You forgot to initialize user with FirebaseAuth.getInstance().currentUser.

Fix:

Move your code that uses user inside the callback where it's defined, or initialize it properly in the correct scope. Example:

// Correct usage: Use user inside the callback
firebaseAuth.signInWithEmailAndPassword(email, password)
    .addOnCompleteListener(this) { task ->
        if (task.isSuccessful) {
            val user = FirebaseAuth.getInstance().currentUser
            val intent = Intent(this, MainActivity::class.java)
            user?.let {
                intent.putExtra("USER_EMAIL", it.email)
            }
            startActivity(intent)
        }
    }

Or if you need user elsewhere in the activity:

// Initialize user at the activity level
private val currentUser = FirebaseAuth.getInstance().currentUser

// Then use it where needed
if (currentUser != null) {
    // Do something with currentUser
}

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

火山引擎 最新活动