我正在尝试处理两个不同Firebase项目的两个数据库。为此,我必须先删除新初始化的应用,然后再重新初始化应用。 为此,我尝试使用但每次都失败。
FirebaseApp.initializeApp(context, firebaseOptions, "secondary").delete();
应该使用什么来删除辅助初始化的Firebase应用程序?这是我的代码下方:
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);
`
答案 0 :(得分:0)
在您的代码中,您找到了辅助实例,但随后立即尝试再次初始化它并抛出错误。
firebaseApp = FirebaseApp.getInstance("secondary");
FirebaseApp.initializeApp(Charts.this, firebaseOptions, "secondary").delete(); // throws IllegalStateException
其固定形式为:
firebaseApp = FirebaseApp.getInstance("secondary");
firebaseApp.delete();
此外,在代码的最后一行,您尝试获取FirebaseApp
而不是firebaseApp
的字符串值的"secondary"
secondaryDatabase = FirebaseDatabase.getInstance(firebaseApp);
此问题的解决方法是:
secondaryDatabase = firebaseApp;
// OR
secondaryDatabase = FirebaseDatabase.getInstance("secondary");
完全不必将应用程序实例存储为firebaseApp
,只需直接删除/使用该实例即可。
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