Manuel Lucas
Manuel Lucas

Reputation: 532

Default FirebaseApp is not initialized in this process com.example.journal. Make sure to call FirebaseApp.initializeApp(Context) first

I was developing an App which consist into a ornithology App, and I was using Firabase as BBDD.

My problem is that I get the following error: 'java.lang.IllegalStateException: Default FirebaseApp is not initialized in this process com.example.journal. Make sure to call FirebaseApp.initializeApp(Context) first.'

I have a first Screen which have a ImageView which associate an OnClickListenner() in charge of send you to the Login Screen. When the App try top send you crash.

Also I'm using the Navigation component in the App, but is not related which the crash.

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();

    }
}

If you have some idea where the error come from, take thanks for advance!

[EDIT]

Add the stacktrace from the error logcat:



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) 


Upvotes: 4

Views: 1436

Answers (1)

Kayes Fahim
Kayes Fahim

Reputation: 690

You're probably missing this line check your build.gadle

apply plugin: 'com.google.gms.google-services'

That fixed it for me.

Upvotes: 4

Related Questions