Search code examples
javaandroidfirebasefirebase-realtime-databasebuild.gradle

No write to database


Trying to use Firebase Realtime Database. I have :

private FirebaseDatabase mFirebaseDatabase;
private DatabaseReference mMessagesDatabaseReference;

In onCreate of main activity I'm trying to write record:

mFirebaseDatabase = FirebaseDatabase.getInstance();
mMessagesDatabaseReference = mFirebaseDatabase.getReference().child("settings");
mMessagesDatabaseReference.push().setValue("aaaa").addOnCompleteListener(new OnCompleteListener<Void>() {

        @Override
        public void onComplete(@NonNull Task<Void> task) {
            if (task.isSuccessful()) {
                Log.d("TAG", "Data written successfully");
            } else {
                Log.d("TAG", "Failed with: " + task.getException().getMessage());
            }
        }

    }).addOnFailureListener(e -> {
        Log.d("TAG", "Failed with: " + e.getMessage()); });

But still have NULL in the Firebase console in the DB browser.

build.gradle has lines:

implementation(platform("com.google.firebase:firebase-bom:32.7.2"))
implementation("com.google.firebase:firebase-database:20.3.0")

What did I do wrong?

UPD

Changed code by adding onComplete and OnFailure listeners. None of events are called.


Solution

  • Your field declarations and the way you are setting the data look good to me. However, the dependencies that exist inside your build.gradle file should follow the official documentation. So when using BOM, there is no need to specify the version of the Realtime Database. So the dependencies should look like this:

    implementation(platform("com.google.firebase:firebase-bom:32.7.2"))
    implementation("com.google.firebase:firebase-database")
    //                                                  👆
    

    Since we cannot see your rules, there might be however some issues. So first of all, stop ignoring errors. At a minimum, you should log the error message if task is not successful. So in code, it should look like this:

    mMessagesDatabaseReference.push().setValue("aaaa").addOnCompleteListener(new OnCompleteListener<Void>() {
        @Override
        public void onComplete(@NonNull Task<Void> task) {
            if (task.isSuccessful()) {
                Log.d("TAG", "Data written successfully");
            } else {
                Log.d("TAG", "Failed with: " + task.getException().getMessage());
            }
        }
    });