How to check if a Firebase App is already initialized on Android

Relm picture Relm · Jun 6, 2016 · Viewed 43.8k times · Source

With the following, the first time it's called it works, but then fails on subsequent calls with "FirebaseApp name [DEFAULT] already exists!"

public FirebaseDatabase conn(Context c) {
         FirebaseOptions options = new FirebaseOptions.Builder()
                .setApiKey("key")
                .setDatabaseUrl("url")
                .setApplicationId("ID")
                .build();


        /////I tried Try and Catch with no success//////
        FirebaseApp app = FirebaseApp.initializeApp(c, options);

        /// for this : FirebaseApp app = FirebaseApp.initializeApp(c, options, "some_app");
        //// will fail with "FirebaseApp name some_app already exists!"
        return FirebaseDatabase.getInstance(app);
}

All of the above is an attempt to connect to a second Firebase App.

Answer

Daniel Laurindo picture Daniel Laurindo · Dec 6, 2016

On firebase web, you check if already initialized with:

if (firebase.apps.length === 0) {
    firebase.initializeApp({});
}