Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 530
Relm Avatar asked Jun 06 '16 08:06

Relm


People also ask

How do I know if an app is connected to Firebase?

If you want to know if the client is connected to the server before calling setValue() , you can attach a listener to . info/connected .

What is firebase app instance?

Instance ID provides a unique identifier for each instance of your app and a mechanism to authenticate and authorize actions, like sending messages via Firebase Cloud Messaging. The InstanceID is long lived, but may expire for the following reasons: Device factory reset.


2 Answers

On firebase web, you check if already initialized with:

if (firebase.apps.length === 0) {     firebase.initializeApp({}); } 
like image 78
Daniel Laurindo Avatar answered Oct 04 '22 19:10

Daniel Laurindo


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

like image 23
Nitin Avatar answered Oct 04 '22 19:10

Nitin