我正在开发一款鸟类学App,并使用Firebase作为BBDD。但是,我遇到了以下错误:“java.lang.IllegalStateException: Default FirebaseApp is not initialized in this process com.example.journal. Make sure to call FirebaseApp.initializeApp(Context) first.”
我的第一个屏幕有一个ImageView,它关联了一个OnClickListenner()来将您发送到登录屏幕。当App尝试发送时会崩溃。
此外,我在App中使用了导航组件,但与崩溃无关。
FirtsScreen.class
public class FirtsScreen extends AppCompatActivity {
private ImageView img;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_firts_screen);
img = (ImageView) findViewById(R.id.imgInicio);
img.setImageResource(R.drawable.inicio);
img.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "WELCOME TO BIRD-LAND !", Toast.LENGTH_LONG).show();
Intent miIntent = new Intent(getApplicationContext(), Login.class);
startActivity(miIntent);
}
});
}
}
MainActivity.class
public class MainActivity extends AppCompatActivity implements FilterDialog.FilterDialogListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView navView = findViewById(R.id.nav_view);
AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
R.id.navigation_home, R.id.navigation_search, R.id.navigation_journal, R.id.navigation_account, R.id.navigation_capture)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
NavigationUI.setupWithNavController(navView, navController);
//Inicializo Firebase.
FirebaseApp.initializeApp(getApplicationContext());
}
@Override
public void getFilters(ArrayList<String> regions) {
SearchFragment fragment = (SearchFragment) getSupportFragmentManager().findFragmentById(R.id.navigation_search);
fragment.receiveRegions(regions);
int i = 0;
i++;
}
}
Login.class
public class Login extends AppCompatActivity {
private EditText EtUser;
private EditText EtPass;
private ImageButton btnLogin;
private String user;
private String pass;
private Usuario usuario;
private FirebaseAuth mAuth;
private FirebaseUser current_user;
private ImageButton btnGoogle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
FirebaseApp.initializeApp(getApplicationContext());
//Todo:Explota aqui porque pide que inicializes FirebaseApp con la linea de arriba, pero aun asi no va.
//Here is the where crash the App.
mAuth = FirebaseAuth.getInstance();
EtUser = (EditText) findViewById(R.id.EtLoginUser);
EtPass = (EditText) findViewById(R.id.EtLoginPass);
btnLogin = (ImageButton) findViewById(R.id.btnLogin);
btnLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
user = EtUser.getText().toString();
pass = EtPass.getText().toString();
usuario = new Usuario(user, pass);
if(!user.isEmpty() && !pass.isEmpty()){
usuario = new Usuario(user, pass);
current_user = FirebaseAuth.getInstance().getCurrentUser();
if (current_user != null) {
// Name, email address, and profile photo Url
String name = current_user.getDisplayName();
String email = current_user.getEmail();
Uri photoUrl = current_user.getPhotoUrl();
// Check if user's email is verified
boolean emailVerified = current_user.isEmailVerified();
// The user's ID, unique to the Firebase project. Do NOT use this value to
// authenticate with your backend server, if you have one. Use
// FirebaseUser.getIdToken() instead.
String uid = current_user.getUid();
}
}else{
Toast.makeText(getApplicationContext(), "Es necesario completar los datos requeridos.", Toast.LENGTH_LONG).show();
}
}
});
btnGoogle = (ImageButton) findViewById(R.id.btnGoogle);
btnGoogle.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
current_user = FirebaseAuth.getInstance().getCurrentUser();
firebaseAuthWithGoogle(current_user.getUid());
}
});
}
private void firebaseAuthWithGoogle(String uid) {
AuthCredential credential = GoogleAuthProvider.getCredential(uid, null);
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "signInWithCredential:success");
FirebaseUser user = mAuth.getCurrentUser();
// Redireccionar a HomeFragment
Navigation.findNavController(btnGoogle).navigate(R.id.fragmentHome);
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithCredential:failure", task.getException());
Toast.makeText(Login.this, "Authentication Failed.", Toast.LENGTH_SHORT).show();
}
}
});
}
@Override
protected void onStart() {
super.onStart();
FirebaseUser currentUser = mAuth.getCurrentUser();
}
private void loginUser(Usuario usuario) {
//TODO:Añadir Firebase Auth.
mAuth.signInWithEmailAndPassword(usuario.getUser(), usuario.getPass()).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
startActivity(new Intent(getApplicationContext(), MainActivity.class));
finish();
}else{
Toast.makeText(getApplicationContext(), "No se pudo iniciar sesión. Compruebe sus datos", Toast.LENGTH_SHORT).show();
}
}
});
//Envio de datos al mainActivity para informar del usuario registrado.
Bundle datos = new Bundle();
datos.putSerializable("User", usuario);
Intent miIntent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(miIntent);
Toast.makeText(getApplicationContext(), "Usuario registrado correctamente", Toast.LENGTH_LONG).show();
}
}
如果您已经有一些关于错误出现原因的想法,请提前致谢!
[编辑]
从错误日志中添加堆栈跟踪:
Caused by: java.lang.IllegalStateException: Default FirebaseApp is not initialized in this process com.example.journal. Make sure to call FirebaseApp.initializeApp(Context) first.
at com.google.firebase.FirebaseApp.getInstance(FirebaseApp.java:183)
at com.google.firebase.auth.FirebaseAuth.getInstance(com.google.firebase:firebase-auth@@20.0.2:1)
at com.example.journal.Login.onCreate(Login.java:49)
at android.app.Activity.performCreate(Activity.java:7802)
at android.app.Activity.performCreate(Activity.java:7791)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1299)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3245)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)