How to check if a Firebase App is already initialized on Android
JavaAndroidGoogle ApiFirebaseFirebase Realtime-DatabaseJava Problem Overview
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.
Java Solutions
Solution 1 - Java
On firebase web, you check if already initialized with:
if (firebase.apps.length === 0) {
firebase.initializeApp({});
}
Solution 2 - Java
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
Solution 3 - Java
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()
Solution 4 - Java
Firebase Version 9
import { initializeApp, getApp } from "firebase/app";
const createFirebaseApp = (config = {}) => {
try {
return getApp();
} catch () {
return initializeApp(config);
}
};
const firebaseApp = createFirebaseApp({/* your config */})
Solution 5 - Java
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);
}
Solution 6 - Java
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.
Solution 7 - Java
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.
Solution 8 - Java
In firebase admin SDK for java, initialize the app if and only if there is no app.
if (FirebaseApp.getApps().isEmpty()) {
FirebaseApp.initializeApp();
}
Solution 9 - Java
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';
Solution 10 - Java
import * as firebase from "firebase/app";
firebase.apps.map(e => e.name); // Give you an array of initialized apps
Solution 11 - Java
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")
});
}
Solution 12 - Java
I faced the similar issue, I resolved it as following:
- Create a var for the application and initialize it with null
- Take reference of the application while initialization
- Check before initializing it again
//global variable
var firebaseResumeDownloadAdd = null;
//inside function check before initializing
if(firebaseResumeDownloadAdd==null){
firebaseResumeDownloadAdd =
firebase.initializeApp(functions.config().firebase);
}
Solution 13 - Java
in Android, depending on Daniel Laurindo's answer:
if (FirebaseApp.getApps(context).size != 0) {
}
Solution 14 - Java
A cleaner solution for ES6+ is
if (!firebase.apps.length) {
...
}
Solution 15 - Java
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"));
Solution 16 - Java
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());
}
Solution 17 - Java
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)
);
}
}