运行RegistrationActivity遇两类错误:清单配置问题与空指针异常求助
Hey there! Let's break down and fix your two issues one by one, step by step.
1. Fixing the "The activity must be exported or contain an intent-filter" Error
This error happens because Android requires any activity that can be launched (either by the system or other components) to either declare itself as exportable or have an intent filter. Here's how to configure your AndroidManifest.xml correctly:
Option 1: If RegistrationActivity is your app's launch screen
Add the main/launcher intent filter to mark it as the entry point of your app:
<activity android:name=".RegistrationActivity" android:exported="true"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity>
Option 2: If RegistrationActivity is only launched by other activities in your app
Just set android:exported="true" to allow internal navigation to it:
<activity android:name=".RegistrationActivity" android:exported="true" />
2. Fixing the java.lang.NullPointerException at the if statement
Looking at your code, there are a couple of issues that could trigger this crash:
Issue 1: Missing semicolon after the AuthStateListener initialization
Your anonymous AuthStateListener definition ends without a semicolon, which causes a syntax error that can lead to unexpected runtime exceptions.
Issue 2: Forgetting to register the AuthStateListener
You created the listener but never attached it to your FirebaseAuth instance, so it won't trigger at all. Plus, we can make the user retrieval more safe by using the firebaseAuth parameter passed to the callback instead of calling getInstance() again.
Corrected Full Code
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_registration); mAuth = FirebaseAuth.getInstance(); // Fix 1: Add semicolon at the end of the listener definition firebaseAuStateListener = new FirebaseAuth.AuthStateListener() { @Override public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) { // Fix 2: Use the provided firebaseAuth instance to get the user final FirebaseUser user = firebaseAuth.getCurrentUser(); if (user != null){ Intent intent = new Intent(RegistrationActivity.this, MainActivity.class); startActivity(intent); finish(); return; } } }; // Fix 3: Register the listener with FirebaseAuth mAuth.addAuthStateListener(firebaseAuStateListener); } // Bonus: Add this to avoid memory leaks by removing the listener when the activity is destroyed @Override protected void onDestroy() { super.onDestroy(); if (firebaseAuStateListener != null) { mAuth.removeAuthStateListener(firebaseAuStateListener); } }
Also, double-check that MainActivity is properly registered in your AndroidManifest.xml too—otherwise, you'll hit a new crash when trying to navigate to it.
内容的提问来源于stack exchange,提问作者Vitor Portella

