javaandroidfirebaseandroid-studio-4.1

Multiple Firebase projects in a single android application


I'm trying to build an android application using Firebase that demands two separate databases (teachers and students) in a single application. I searched for the solution all over the internet but all I got is this solution- Multiple Firebase projects in one app, which seems to be a great solution but I didn't understand.

So, how do I merge two firebase projects in a single application?


Solution

  • Yes, you can follow that guide https://firebase.google.com/docs/projects/multiprojects#java.

    Basically, you need to initiate the firebase app providing configuration manually

            // [START firebase_options]
        // Manually configure Firebase Options. The following fields are REQUIRED:
        //   - Project ID
        //   - App ID
        //   - API Key
        FirebaseOptions options1 = new FirebaseOptions.Builder()
                .setProjectId("my-firebase-project")
                .setApplicationId("1:27992087142:android:ce3b6448250083d1")
                .setApiKey("AIzaSyADUe90ULnQDuGShD9W23RDP0xmeDc6Mvw")
                // setDatabaseURL(...)
                // setStorageBucket(...)
                .build();
        FirebaseOptions options2 = new FirebaseOptions.Builder()
                .setProjectId("my-firebase-project")
                .setApplicationId("1:27992087142:android:ce3b6448250083d1")
                .setApiKey("AIzaSyADUe90ULnQDuGShD9W23RDP0xmeDc6Mvw")
                // setDatabaseURL(...)
                // setStorageBucket(...)
                .build();
        // [END firebase_options]
    
    
        // [START firebase_secondary]
        // Initialize with secondary app
        FirebaseApp.initializeApp(this /* Context */, options1, "first");
        FirebaseApp.initializeApp(this /* Context */, options2, "secondary");
    
    
        FirebaseApp first = FirebaseApp.getInstance("first");
        FirebaseApp secondary = FirebaseApp.getInstance("secondary");
    

    You can get all required data from google-service.json

    enter image description here

    enter image description here

    Later you can get a database from that FirebaseApp, for example

    FirebaseDatabase secondaryDatabase = FirebaseDatabase.getInstance(secondary);
    

    Then you just work with the project like before.