19

I'm trying to have one project in Firebase that will be responsible for one common thing that all Apps.

That is, I want to create Apps, then have these Apps access a particular Firebase Database of a project.

Looking at the Firebase Android docs, I can't find a way to send data to another firebase database in another project using the following, but where reference is of another project.

DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("example");
        ref.push().setValue(d).addOnCompleteListener(new OnCompleteListener<Void>() {
            @Override
            public void onComplete(@NonNull Task<Void> task) {
                finish();
            }
        });
Relm
  • 7,923
  • 18
  • 66
  • 113

1 Answers1

38

You'll need to initialize a second FirebaseApp object with explicit options in your code:

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

I got the configuration values from the second project's google-services.json. The API Key is under a property called api_key, the Application ID came from a property called mobilesdk_app_id and the database URL came from a property called firebase_url.

Also see the documentation on using multiple projects in your application.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • App crushes with. "FirebaseApp name [DEFAULT] already exists!" – Relm Jun 05 '16 at 17:17
  • 1
    Sorry about that. I'll add an second "guess". If that's still not working, I'll pull out Android Studio. – Frank van Puffelen Jun 05 '16 at 19:22
  • Ok, still have issues, whatever I add there as the third argument crushes the app with error, "FirebaseApp name $app_name already exists!", even if is not one of my Apps in the console. – Relm Jun 05 '16 at 20:25
  • Also for others, ApplicationID is required for FirebaseOptions.Builder() – Relm Jun 05 '16 at 20:28
  • I just tested the latest code snippet again in a clean project and it works without problems. If you're still having problems, you'll have to add some more details. – Frank van Puffelen Jun 08 '16 at 18:43
  • "IllegalStateException: FirebaseApp name second app already exists!". On the first call, this error doesn't happen, but then it crushes on subsequent calls. What would be the way to check if "this" app was initialised? – Relm Jun 08 '16 at 20:12
  • 1
    I typically ensure that I only initialize the apps once by having them in a single activity or a content provider. But if you want to check, you can loop over the apps with `for (FirebaseApp app: FirebaseApp.getApps(getApplicationContext())) ...` or `FirebaseApp.getInstance("secondApp") == null` – Frank van Puffelen Jun 08 '16 at 21:19
  • 2
    I put it inside a try catch. try { FirebaseApp app = FirebaseApp.initializeApp(c, options, "app"); return FirebaseDatabase.getInstance(app); } catch (IllegalStateException e){ return FirebaseDatabase.getInstance(FirebaseApp.getInstance("app")); } ///and that works. – Relm Jun 09 '16 at 06:53
  • I'm driving crazy : I followed your advice two days ago, @FrankvanPuffelen , and it worked perfectly. Today, I relaunch my app... I get absolutely nothing : nor error, neither crash... just nothing. My ref url is good when I log it just before adding a listener, but it never fires OnChildAdded, nor Cancelled. I wasn't crazy, and it worked, so what ? (all queries linked to the "main" Firebase database are ok and work well). Is there a security issue set by Firebase ? – PAD Jun 27 '16 at 18:23
  • I have a similar problem. In my case the app is working fine with Firebase but I want to move to the new Google Cloud Messaging powered by Firebase. I have GCM in a different google project, how can I merge that project into my existing Firebase? Otherwise I would be registering users now using different project and that's a total mess. – Roberto Jun 29 '16 at 14:40
  • Hi, I am getting 09-18 15:48:19.891: E/AndroidRuntime(4975): java.lang.NoClassDefFoundError: Failed resolution of: Lcom/google/android/gms/common/internal/zzab; 09-18 15:48:19.891: E/AndroidRuntime(4975): at com.google.firebase.FirebaseOptions$Builder.setApplicationId(Unknown Source) exception .... kindly hep me. It's urgent – Soubhab Pathak Sep 18 '16 at 10:20
  • 1
    @FrankvanPuffelen Sir, but what about auth, I mean if i want to register a user with email/pass from second app into firstApp's database? Can i use it like this: FirebaseAuth auth = FirebaseAuth.getInstance(secondApp); ? – Abhinav Raja Oct 10 '16 at 20:26
  • @Relm Same as you, I get App crushes with. "FirebaseApp name [DEFAULT] already exists!" This answer isn't reliable and you shouldn't have marked it as correct if it's not working out of the box – Jaythaking Oct 12 '16 at 20:48
  • @Jaythaking that error means that you're initializing the default app twice, which is not related to this answer. But see my earlier comment about that problem: http://stackoverflow.com/questions/37634767/how-to-connect-to-more-than-one-firebase-database-from-an-android-app/37643374?noredirect=1#comment62899818_37643374 – Frank van Puffelen Oct 13 '16 at 08:35
  • Yeah but that line raised an exception : FirebaseApp.getInstance("secondApp") == null... It's surprising how much of a hassle just to perform such a simple thing, I'm stunned – Jaythaking Oct 13 '16 at 15:02
  • @FrankvanPuffelen Could you please shed some light on my related question https://stackoverflow.com/questions/44866220 – bibscy Jul 02 '17 at 12:57