yesterdaysfoe
yesterdaysfoe

Reputation: 808

FirebaseApp name [DEFAULT] already exists

I'm trying to manually initialize FirebaseApp on Application but getting this error.

public class BaseApplication extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
        FirebaseOptions firebaseOptions = new FirebaseOptions.Builder()
              .setDatabaseUrl("[DATABASE_URL]")
              .setApiKey("API_KEY")
              .setApplicationId("PROJECT_ID").build();
        FirebaseApp.initializeApp(getApplicationContext(),firebaseOptions);

        if (!FirebaseApp.getApps(this).isEmpty()) {
            FirebaseDatabase.getInstance().setPersistenceEnabled(true);
        }
    }

Assume that I set the firebaseOptions value accordingly. I am expecting that this will set values for FirebaseApp.

Did I missed something? FirebaseApp Documentation

The default app instance is initialized on app startup by FirebaseInitProvider. This is added to the app's manifest by Gradle manifest merging. If the app is using a different build system the provider needs to be manually added to the app's manifest.

Alternatively initializeApp(Context, FirebaseOptions) initializes the default app instance. This method should be invoked from Application. This is also necessary if it is used outside of the application's main process.

   FATAL EXCEPTION: main
    Process: com.sample.android, PID: 5490
    java.lang.RuntimeException: Unable to create application com.android.tools.fd.runtime.BootstrapApplication: java.lang.IllegalStateException: FirebaseApp name [DEFAULT] already exists!
    at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4331)
    at android.app.ActivityThread.access$1500(ActivityThread.java:135)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:136)
    at android.app.ActivityThread.main(ActivityThread.java:5001)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:515)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:801)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:617)
    at dalvik.system.NativeStart.main(Native Method)
    Caused by: java.lang.IllegalStateException: FirebaseApp name [DEFAULT] already exists!
    at com.google.android.gms.common.internal.zzab.zza(Unknown Source)
    at com.google.firebase.FirebaseApp.initializeApp(Unknown Source)
    at com.sample.android.activities.BcodeApplication.onCreate(BcodeApplication.java:21)
    at com.android.tools.fd.runtime.BootstrapApplication.onCreate(BootstrapApplication.java:369)
    at android.app.Instrumentation.callApplicationOnCreate(Instrumentation.java:1007)
    at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4328)
    at android.app.ActivityThread.access$1500(ActivityThread.java:135) 
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256) 
    at android.os.Handler.dispatchMessage(Handler.java:102) 
    at android.os.Looper.loop(Looper.java:136) 
    at android.app.ActivityThread.main(ActivityThread.java:5001) 
    at java.lang.reflect.Method.invokeNative(Native Method) 
    at java.lang.reflect.Method.invoke(Method.java:515) 
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:801) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:617) 
    at dalvik.system.NativeStart.main(Native Method) 

Upvotes: 32

Views: 39498

Answers (8)

sati.mobileapp
sati.mobileapp

Reputation: 1

Just wrap it with try and catch.

try{
FirebaseApp.initializeApp(getApplicationContext(),firebaseOptions);
}catch(_){}

Upvotes: 0

RKALM
RKALM

Reputation: 114

I believe I understand what you wish to do, (you are doing multi-threaded programming right? I guessed that from the if empty). I assume that you wish an automated way to add a new FirebaseApp each time you run a specific thread. If that is the case. that is the way I solved it. I added a random generator to give name each time.

Here is my code:

SecureRandom random = new SecureRandom();
options = new FirebaseOptions.Builder()
                .setCredentials(credentials)
                .build();
        String name = String.valueOf(random.nextInt());
        FirebaseApp.initializeApp(options,name);
    db = FirestoreClient.getFirestore(FirebaseApp.getInstance(name));

Upvotes: 0

Mohammad AlShaabi
Mohammad AlShaabi

Reputation: 79

I suggest that you search in the whole project for "FirebaseApp.InitializeApp", there is a chance that you have already initialized it somewhere else and forgot about it specially if you are following a tutorial or you are modifying an open source project from GitHub for example.

sometimes the error message is so simple that makes us ignore it, since the error says "already exists" then give it a chance and search for it.

Upvotes: 0

Vishal Kumar
Vishal Kumar

Reputation: 517

You can just check if it's active or not:

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

Upvotes: 3

CodeToLife
CodeToLife

Reputation: 4151

In onCreate():

    ...                                                                    
      if (!checkInternet()) {
        showMessageDialog("Enable Internet connection please.", true);
        finish();

    } else {

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

        FirebaseOptions options = new FirebaseOptions.Builder()
                .setApiKey("AIzaSyA6172grz_K_jkhfvXsrUUiug9LwImK3sg26bE")//https://console.developers.google.com/apis/credentials?project=speachgapimytest-72e23
                .setApplicationId("uz.my.speach.gapi")
                .setDatabaseUrl("https://speachgapimytest-72e23.firebaseio.com/")
                .build();
        if (!hasBeenInitialized) 
            fbApp = FirebaseApp.initializeApp(getApplicationContext(), options, "SpeachGAPIMaximTest"/*""*/);
        else
            fbApp = FirebaseApp.getInstance("SpeachGAPIMyTest");
        fbDB = FirebaseDatabase.getInstance(fbApp); 

        startAuthDialog();                                                
        ...


    }

Upvotes: 3

checkmate711
checkmate711

Reputation: 3461

Actually it is possible to replace the default FirebaseApp based on this blog post here.

The steps would be to: 1. Disable the FirebaseInitProvider in the Android Manifest

<provider
    android:name="com.google.firebase.provider.FirebaseInitProvider"
    android:authorities="${applicationId}.firebaseinitprovider"
    tools:node="remove"
    />

2. Create your own ContentProvider, register it in the AndroidManifest. As a sample you can use the FirebaseInitProvider. Inside, create the Firebase default app using the FirebaseOptions builder.

FirebaseOptions.Builder builder = new FirebaseOptions.Builder()
    .setApplicationId("1:0123456789012:android:0123456789abcdef")
    .setApiKey("your_api_key")
    .setDatabaseUrl("https://your-app.firebaseio.com")
    .setStorageBucket("your-app.appspot.com");
FirebaseApp.initializeApp(this, builder.build());

Upvotes: 7

Riyas PK
Riyas PK

Reputation: 3217

Use this

FirebaseOptions options = new FirebaseOptions.Builder()
    .setApiKey(apiKey)
    .setApplicationId(appId)
    .setDatabaseUrl(firebaseBaseUrl)
    .build();

boolean hasBeenInitialized=false;
List<FirebaseApp> firebaseApps = FirebaseApp.getApps(mContext);
for(FirebaseApp app : firebaseApps){
    if(app.getName().equals(FirebaseApp.DEFAULT_APP_NAME)){
        hasBeenInitialized=true;
        finestayApp = app;
    }
}

if(!hasBeenInitialized) {
    finestayApp = FirebaseApp.initializeApp(mContext, options);
}

Upvotes: 25

Bob Snyder
Bob Snyder

Reputation: 38289

It's not clear what your goal is. If you simply want to modify ("overwrite") the default FirebaseApp that is created by FirebaseInitProvider, I don't think that is possible. The documentation you cited is a little misleading in that it suggests it is possible. I think the documentation is intended to describe how the default app can be initialized when it has not already been created, for example in a secondary process.

You can use FirebaseApp.initializeApp() to create another app object. You need to use the method that accepts a parameter for the app name:

    FirebaseOptions firebaseOptions = new FirebaseOptions.Builder()
          .setDatabaseUrl("[DATABASE_URL]")
          .setApiKey("API_KEY")
          .setApplicationId("PROJECT_ID").build();

    FirebaseApp myApp = FirebaseApp.initializeApp(getApplicationContext(),firebaseOptions,
        "MyAppName");

You can then use the created FirebaseApp to get an instance of FirebaseDatabase, FirebaseStorage, FirebaseAuth, FirebaseCrash, or FirebaseInstanceId. For example:

FirebaseDatabase database = FirebaseDatabase.getInstance(myApp);

In an app's main process, I don't think there is a simple way to disable the initialization processing done by FirebaseInitProvider. If you want to override the configuration parameters that normally come from google-services.json, you can probably create your own XML file for the parameters using the information in the documentation for the Google Services Plugin. It states:

If your Android project has some configuration that prevents you from using the google-services plugin, you can safely recreate the XML files manually using these values

I don't know how simple or maintainable that is.

Upvotes: 21

Related Questions