schmidi000 schmidi000 - 1 year ago 114
Java Question

Java EE FirebaseApp name [DEFAULT] already exists

I got a problem related to Firebase and Java EE.

I'm currently writing some Java servlets for my project and I'm using Firebase the first time because I wanted to try something new.

My actual problem is the following:
I got a servlet which is responsible for exchanging an iOS device token in an user database. This is necessary for sending Remote Push Notifications to a device.
I've done this like in the google tutorials, but I'm getting the following exception:

java.lang.IllegalStateException: FirebaseApp name [DEFAULT] already exists!

The way I'm accessing the Firebase Database is through the Java SDK.

I do this with the following code:

connect method

// gets called by the servlet to configure Firebase
public static void connect() {
try {
// for authentication purpose
Map<String, Object> auth = new HashMap<>();
auth.put("uid", "my-service-account");

// Setting up the FirebaseOptions object
// constant FIREBASE_DATABASE_URL = "url to my database"
// constant FIREBASE_KEY_PATH = "path to my json key"
options = new FirebaseOptions.Builder()
.setServiceAccount(new FileInputStream(FIREBASE_KEY_PATH))


// calling the method for exchanging the token
exchangeIosDeviceToken("[email protected]", "5bf53173c9ef0a37638f3ddaa59cf2c0687c14ca0dcd47ccf57f9f09bd6368ab");
} catch (FileNotFoundException ex) {

exchangeIosDeviceToken method

public static boolean exchangeIosDeviceToken(String email, String newDeviceToken) {
FirebaseDatabase database = FirebaseDatabase.getInstance();

// getting a reference to my "employee" child
DatabaseReference employeeReference = database.getReference("/employee");

Map<String, Object> employeeUpdates = new HashMap<>();
// updating the device token with child "iosDeviceToken" of "employee"
employeeUpdates.put(email+"/iosDeviceToken", newDeviceToken);

// update the actual children
return true;

The funny part is when I'm trying to execute this code in a standalone main class (replacing the connect method, with the main method), the code is working.

Before you're saying things like "there are tons of questions related to this topic"... They are nearly all related to Android and questions related to my problem seldom got answered.


Answer Source

Solved the problem.

The problem was: I've called the connect method everytime a request was incoming.

Solution: Call the connect method only once. (ServletContextListener)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download