Android切换登录时SharedPreference用户名更新问题求助
Hey there! Let's fix this username display issue step by step—since you're new to Android, I'll keep things clear and actionable.
The root cause here is that you're relying on SharedPreferences to store the username, but when you switch users, you aren't updating that stored value or fetching the current logged-in user's info directly from Firebase Auth. SharedPreferences keeps old data unless you explicitly overwrite it, which is why you see the previous user's name.
Step 1: Update SharedPreferences when a new user logs in
When your login request succeeds (after Firebase validates the credentials), grab the current user's details from Firebase Auth and save them to SharedPreferences. Here's how to modify your login logic:
// Inside your ManualLogin activity's login handling code FirebaseAuth.getInstance().signInWithEmailAndPassword(email, password) .addOnCompleteListener(this, task -> { if (task.isSuccessful()) { // Get the currently logged-in user from Firebase FirebaseUser currentUser = FirebaseAuth.getInstance().getCurrentUser(); if (currentUser != null) { // Use displayName if your users set one during registration, else fall back to email String username = currentUser.getDisplayName() != null ? currentUser.getDisplayName() : currentUser.getEmail(); // Save the new username to SharedPreferences SharedPreferences prefs = getSharedPreferences("MyAppPrefs", MODE_PRIVATE); SharedPreferences.Editor editor = prefs.edit(); editor.putString("saved_username", username); editor.apply(); // Async save (better for UI thread) // Navigate to your home screen or update the UI Toast.makeText(ManualLogin.this, "Login successful!", Toast.LENGTH_SHORT).show(); startActivity(new Intent(ManualLogin.this, HomeActivity.class)); finish(); } } else { // Handle login failure (e.g., wrong password) Toast.makeText(ManualLogin.this, "Login failed: " + task.getException().getMessage(), Toast.LENGTH_SHORT).show(); } });
Step 2: Fetch the current user directly from Firebase Auth when loading the UI
Don't just rely on SharedPreferences—always check Firebase Auth first when displaying the username (like in onCreate or onResume of your home activity). This ensures you get the latest logged-in user, even if they switched accounts outside your app:
// In your home activity's onCreate method @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_home); TextView usernameDisplay = findViewById(R.id.tv_welcome_username); FirebaseUser currentUser = FirebaseAuth.getInstance().getCurrentUser(); if (currentUser != null) { String currentUsername = currentUser.getDisplayName() != null ? currentUser.getDisplayName() : currentUser.getEmail(); // Update the UI with the real current username usernameDisplay.setText("Welcome, " + currentUsername); // Optional: Update SharedPreferences here to keep it in sync SharedPreferences prefs = getSharedPreferences("MyAppPrefs", MODE_PRIVATE); SharedPreferences.Editor editor = prefs.edit(); editor.putString("saved_username", currentUsername); editor.apply(); } else { // No user logged in—redirect to login screen startActivity(new Intent(this, ManualLogin.class)); finish(); } }
Step 3: Clear SharedPreferences when the user signs out
When the user taps "Sign Out", make sure to erase the stored username so the next login doesn't show old data:
// Example sign-out button click listener in your home activity buttonSignOut.setOnClickListener(v -> { FirebaseAuth.getInstance().signOut(); // Clear the saved username from SharedPreferences SharedPreferences prefs = getSharedPreferences("MyAppPrefs", MODE_PRIVATE); SharedPreferences.Editor editor = prefs.edit(); editor.remove("saved_username"); // Or use editor.clear() to delete all stored data editor.apply(); // Send user back to login screen startActivity(new Intent(this, ManualLogin.class)); finish(); });
Quick Tips for Beginners
FirebaseAuth.getInstance().getCurrentUser()is your single source of truth for logged-in user info—never trust SharedPreferences alone, since it can be outdated.- SharedPreferences is great for caching small data, but always validate it against Firebase's current user state.
- If you don't collect display names during registration, using the user's email as the username is a safe fallback.
内容的提问来源于stack exchange,提问作者Jatin Bhatia

