90

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.

Relm
  • 7,156
  • 17
  • 61
  • 106

17 Answers17

214

On firebase web, you check if already initialized with:

if (firebase.apps.length === 0) {
    firebase.initializeApp({});
}
Franck Jeannin
  • 4,840
  • 3
  • 19
  • 31
Daniel Laurindo
  • 2,508
  • 1
  • 13
  • 4
37

In v9, Firebase has been modularized for better tree shaking. So we can no longer import entire app and check the apps property AFAIK. The below approach can be used instead.

import { initializeApp, getApps, getApp } from "firebase/app";
getApps().length === 0 ? initializeApp(firebaseConfig) : getApp();

https://firebase.google.com/docs/reference/js/v9/app.md#getapps for documentation

Nitin
  • 6,339
  • 6
  • 28
  • 34
  • I tried this but I get this error - https://stackoverflow.com/questions/72028182/how-to-initialize-firebase-in-firebase-version-9-firebase-v9/72029160#72029160 – user3399180 Apr 28 '22 at 05:00
16

For those wondering how to do the same as the accepted answer, in Android:

if (FirebaseApp.getApps(context).isEmpty()) {
    FirebaseApp.initializeApp(context);
}

and in an instrumented test environment, use this context:

InstrumentationRegistry.getContext()
Nick Cardoso
  • 19,801
  • 12
  • 67
  • 115
14

Firebase Version 9

import { initializeApp, getApp } from "firebase/app";

const createFirebaseApp = (config = {}) => {
  try {
    return getApp();
  } catch () {
    return initializeApp(config);
  }
};

const firebaseApp = createFirebaseApp({/* your config */})
Max Ma
  • 880
  • 8
  • 13
7

You can try to get the Firebase app instance, in it's code firebase checks if it's initialized, if not it throws an IllegalStateException.

    try{
        FirebaseApp.getInstance();
    }
    catch (IllegalStateException e)
    {
        //Firebase not initialized automatically, do it manually
        FirebaseApp.initializeApp(this);
    }
Jorge Arimany
  • 5,409
  • 2
  • 27
  • 22
6

I think what you want to do is check the list of running apps before initializing your app. Each of the SDKs have a method for getting this array, in android it's getApps:

https://firebase.google.com/docs/reference/android/com/google/firebase/FirebaseApp.html

Then you can check to see if your app is already initialized.

In my case I just ended up checking the length of the array (I'm using the javascript / web sdk so I'm sure it's a little different for Android) and initializing a new app if it is 0.

KCE
  • 1,089
  • 7
  • 24
2

I faced the similar issue. I solved the following problem by deleting the already initialized app.

    // Access your firebase app
    let app = firebase.app();
    // Delete your app.
    app.delete(app);

Solution works for web.

2

In firebase admin SDK for java, initialize the app if and only if there is no app.

if (FirebaseApp.getApps().isEmpty()) {
    FirebaseApp.initializeApp();
}
Ratul Sharker
  • 6,821
  • 2
  • 31
  • 41
1

Not sure in android, but how about using a singleton method. In JS you can do this. Hope this helps someone

// Config file
import * as firebase from "firebase";

const config = {...};

export default !firebase.apps.length ? firebase.initializeApp(config) : firebase.app();

// Other file
import firebase from '../firebase';
rMili
  • 106
  • 7
1
import * as firebase from "firebase/app";
firebase.apps.map(e => e.name); // Give you an array of initialized apps
Jürgen Brandstetter
  • 6,226
  • 3
  • 33
  • 30
1

For those who are using dotNet FirebaseAdmin SDK

if (FirebaseApp.GetInstance("[DEFAULT]") == null)
{
    var createdApp = FirebaseApp.Create(new AppOptions()
    {
        Credential = GoogleCredential.FromFile("private-key.json")
    });
}
Zeeshan Ahmad Khalil
  • 775
  • 1
  • 13
  • 26
0

I faced the similar issue, I resolved it as following:

  1. Create a var for the application and initialize it with null
  2. Take reference of the application while initialization
  3. Check before initializing it again

//global variable
var firebaseResumeDownloadAdd = null;

//inside function check before initializing
if(firebaseResumeDownloadAdd==null){
   firebaseResumeDownloadAdd =
   firebase.initializeApp(functions.config().firebase);
}
0

in Android, depending on Daniel Laurindo's answer:

if (FirebaseApp.getApps(context).size != 0) {

} 
Harshad Pansuriya
  • 19,001
  • 8
  • 65
  • 90
Mina Farid
  • 3,355
  • 4
  • 30
  • 39
0

A cleaner solution for ES6+ is


if (!firebase.apps.length) {
 ...
}
mr3mo
  • 125
  • 10
0

Simple use Java 8 Stream and Optional featured.

Code below as

FirebaseApp.getApps()
.stream()
.filter(firebaseApp -> 
    firebaseApp.getName().equals("APP_NAME"))
   .findFirst()
   .orElseGet(() -> FirebaseApp.initializeApp(firebaseOptions, "APP_NAME"));
Yasir Shabbir Choudhary
  • 2,258
  • 2
  • 26
  • 30
0

Th Use Platform check to initialize according to environment

On firebase web, you check if already initialized with

use the below snippet while launching MYAPP()

import 'dart:io';

void main() async {

WidgetsFlutterBinding.ensureInitialized();

if (Platform.isAndroid || Platform.isIOS) {

await Firebase.initializeApp();

} else {

if (Firebase.apps.isEmpty) {

  await Firebase.initializeApp(

      // connect for web to firebase
      options:firebaseOptions

}

} runApp(const MyApp());

}

awes0m
  • 1
  • 1
-1

If you are using Nativescript to build an hybrid mobile app for Android | iOS you can use this script:

import * as firebase from 'nativescript-plugin-firebase';

_initFirebase(): Promise<any> {
    if (!(firebase as any).initialized) {
      return firebase.init({}).then(
        () => {
          console.info('firebase started...');
        },
        (error) => console.error(error)
      );
    }
  }


edyrkaj
  • 69
  • 1
  • 3