A. Omar A. Omar - 3 months ago 41
Android Question

"Firebase App named '[DEFAULT]' already exists."

So I was trying to use Firebase in an Android service which is in a seperate process and this error came up while doing:

FirebaseDatabase.getInstance()....
or
FirebaseAuth.getInstance()....


I wrote this check snippet to overcome the problem:

boolean hasBeenInitialized=false;
List<FirebaseApp> firebaseApps = FirebaseApp.getApps(this);
for(FirebaseApp app : firebaseApps){
if(app.getName().equals("[DEFAULT]")){
hasBeenInitialized=true;
}
}

if(!hasBeenInitialized) {
FirebaseApp.initializeApp(this, FirebaseOptions.fromResource(this));
}

// Only then getInstance() will work


And IT WORKS pretty good BUT I'm not sure this is the right way to do it (it's the hardcoded
[DEFAULT]
that bothers me...).

Does anyone knows a proper way to do this ?

Answer

You can compare to FirebaseApp.DEFAULT_APP_NAME instead. See the reference docs.