I'm try to handle two databases of two different firebase projects. For this I have to first Delete newly initialized app and then have to re-initialized app. For this purpose I'm trying to use but failed everytime.
FirebaseApp.initializeApp(context, firebaseOptions, "secondary").delete();
What should be used to Delete an secondary initialized firebase app? Here's below my code:
boolean hasBeenInitialized = false;
List<FirebaseApp> firebaseAppList = FirebaseApp.getApps(Charts.this);
for (FirebaseApp app : firebaseAppList) {
if (app.getName().equals("secondary")) {
hasBeenInitialized = true;
}
}
FirebaseOptions firebaseOptions = new FirebaseOptions.Builder()
.setApiKey(apiKey)
.setApplicationId(appId)
.setDatabaseUrl(databaseLink)
.build();
if (!hasBeenInitialized) { //false
firebaseApp = FirebaseApp.initializeApp(Charts.this, firebaseOptions, "secondary");
} else {
firebaseApp = FirebaseApp.getInstance("secondary");
FirebaseApp.initializeApp(Charts.this, firebaseOptions, "secondary").delete();
firebaseApp = FirebaseApp.initializeApp(Charts.this, firebaseOptions, "secondary");
}
secondaryDatabase = FirebaseDatabase.getInstance(firebaseApp);
`
In your code, you find the secondary instance, but then immediately try to initialize it again throwing an error.
firebaseApp = FirebaseApp.getInstance("secondary");
FirebaseApp.initializeApp(Charts.this, firebaseOptions, "secondary").delete(); // throws IllegalStateException
The fixed form of this would be:
firebaseApp = FirebaseApp.getInstance("secondary");
firebaseApp.delete();
Also, on the last line of your code, you try to get the FirebaseApp
for the string value of firebaseApp
not "secondary"
secondaryDatabase = FirebaseDatabase.getInstance(firebaseApp);
The fixed from of this would be:
secondaryDatabase = firebaseApp;
// OR
secondaryDatabase = FirebaseDatabase.getInstance("secondary");
Instead of storing the app instance as firebaseApp
at all, just delete/use the instance directly.
List<FirebaseApp> firebaseAppList = FirebaseApp.getApps(Charts.this);
// Delete "secondary" if it exists
for (FirebaseApp app : firebaseAppList) {
if (app.getName().equals("secondary")) {
app.delete(); // found "secondary". Delete it
break;
}
}
// Build options object
FirebaseOptions firebaseOptions = new FirebaseOptions.Builder()
.setApiKey(apiKey)
.setApplicationId(appId)
.setDatabaseUrl(databaseLink)
.build();
// Initialize
secondaryDatabase = FirebaseApp.initializeApp(Charts.this, firebaseOptions, "secondary");
// secondaryDatabase is now a FirebaseApp instance for the secondary database
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With