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

Issue

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.

Solution

On firebase web, you check if already initialized with:

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

Answered By – Daniel Laurindo

Answer Checked By – David Goodson (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *