Search code examples
javaandroidfirebasefirebase-realtime-databasefirebase-console

Select Firebase database in runtime


I would like to give the user the option to select which Firebase Real-time database to use. Essentially I am using multiple Firebase databases in a single apk. As this happens in runtime I won’t be able to use the google-services.json file to connect to Firebase. I used this blog as reference but still couldn’t connect to the database .


Blog post

Blog post - https://firebase.googleblog.com/2017/03/take-control-of-your-firebase-init-on.html?m=1


Is there a solution where I could connect to Firebase database in runtime.


Solution

  • If you can't rely on the google services plugin to read the data from google-services.json, you can also specify the relevant data in your code when you initialize the FirebaseApp instance:

    FirebaseOptions options = new FirebaseOptions.Builder()
            .setApiKey("AI...j0")
            .setApplicationId("1:5...e0")
            .setDatabaseUrl("https://myapp.firebaseio.com")
            .build();
    FirebaseApp firebaseApp = FirebaseApp.initializeApp(getApplicationContext(), options, "second app");
    FirebaseDatabase database = FirebaseDatabase.getInstance(firebaseApp);
    database.getReference().setValue(ServerValue.TIMESTAMP);
    

    You will have to get the relevant values from the google-services.json or the Firebase console.

    Also see my answer here: How to connect to more than one firebase database from an android App