Firebase登录后获取用户信息异常:姓名地址无法显示在TextView
Hey there! Let's troubleshoot why your user's name and address aren't showing up in the TextView. Your code has the foundation, but we're missing key steps to fetch and bind the Firebase data properly. Here's a step-by-step solution:
1. Complete the TextView Initialization
First, you need to connect your userName TextView variable to the actual UI element in your layout. Add this line inside onCreate() after setting the content view:
userName = findViewById(R.id.your_username_textview_id); // Replace with your actual TextView ID
(Don't forget to do the same for your address TextView if you have one!)
2. Fetch the Current User's UID
To target the right user data in Firebase, you need the unique ID (UID) of the currently logged-in user. Add this logic to get the UID and handle cases where no user is logged in:
FirebaseUser currentUser = FirebaseAuth.getInstance().getCurrentUser(); if (currentUser == null) { // Redirect to login or show an error message Toast.makeText(this, "Please log in first", Toast.LENGTH_SHORT).show(); finish(); return; } String userId = currentUser.getUid();
3. Target the Correct Database Node & Listen for Data
Your current userReference points to the root of the database. You need to narrow it down to the specific user's node (usually structured like users/{userId}). Then add a listener to fetch the data:
Option 1: Fetch Once (Single Read)
Use this if you don't need real-time updates:
// Point to the specific user's data DatabaseReference userRef = FirebaseDatabase.getInstance().getReference("users").child(userId); userRef.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { if (dataSnapshot.exists()) { // Get the user's name (adjust the child name to match your database structure) String name = dataSnapshot.child("name").getValue(String.class); String address = dataSnapshot.child("address").getValue(String.class); // Set the values to your TextViews userName.setText(name); // Do the same for your address TextView: addressTextView.setText(address); } else { Toast.makeText(UserProfileActivity.this, "User data not found", Toast.LENGTH_SHORT).show(); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { // Handle errors (e.g., permission denied) Toast.makeText(UserProfileActivity.this, "Failed to load data: " + databaseError.getMessage(), Toast.LENGTH_SHORT).show(); } });
Option 2: Real-Time Updates
Use this if you want the TextView to update automatically when the user's data changes in Firebase:
DatabaseReference userRef = FirebaseDatabase.getInstance().getReference("users").child(userId); userRef.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { if (dataSnapshot.exists()) { String name = dataSnapshot.child("name").getValue(String.class); String address = dataSnapshot.child("address").getValue(String.class); userName.setText(name); // addressTextView.setText(address); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { Toast.makeText(UserProfileActivity.this, "Error: " + databaseError.getMessage(), Toast.LENGTH_SHORT).show(); } });
4. Critical Checks to Avoid Issues
- Database Structure: Make sure your Firebase database has a
usersnode, with each user's data stored under their UID, like this:{ "users": { "abc123xyz": { "name": "John Doe", "address": "123 Main St" } } } - Security Rules: Ensure your Firebase Database Rules allow read access. For testing, you can temporarily use:
(Never leave open rules like{ "rules": { "users": { "$uid": { ".read": "$uid === auth.uid", ".write": "$uid === auth.uid" } } } }".read": truein production!) - TextView IDs: Double-check that the ID you use in
findViewById()matches the ID in youractivity_user_profile.xmllayout file.
Full Corrected Code
Here's how your complete UserProfileActivity should look:
public class UserProfileActivity extends AppCompatActivity { DatabaseReference userReference; TextView userName, userAddress; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_user_profile); // Replace with your actual layout name // Initialize TextViews userName = findViewById(R.id.tv_user_name); userAddress = findViewById(R.id.tv_user_address); // Get current logged-in user FirebaseUser currentUser = FirebaseAuth.getInstance().getCurrentUser(); if (currentUser == null) { Toast.makeText(this, "Please log in to view profile", Toast.LENGTH_SHORT).show(); finish(); return; } String userId = currentUser.getUid(); // Point to user's data in Firebase userReference = FirebaseDatabase.getInstance().getReference("users").child(userId); // Fetch and display data (real-time update version) userReference.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { if (dataSnapshot.exists()) { String name = dataSnapshot.child("name").getValue(String.class); String address = dataSnapshot.child("address").getValue(String.class); userName.setText(name); userAddress.setText(address); } else { Toast.makeText(UserProfileActivity.this, "No profile data found", Toast.LENGTH_SHORT).show(); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { Toast.makeText(UserProfileActivity.this, "Failed to load profile: " + databaseError.getMessage(), Toast.LENGTH_SHORT).show(); } }); } }
内容的提问来源于stack exchange,提问作者S.Byrne

