Tapas Mukherjee
Tapas Mukherjee

Reputation: 2178

Data not getting saved in Firebase database from android

I am using the new Firebase console. I am trying to save an object to the database but its not getting saved. Following is the code.

DatabaseReference mFirebaseRef = FirebaseDatabase.getInstance().getReference();
mFirebaseRef.push().setValue(object, new DatabaseReference.CompletionListener() {
            @Override
            public void onComplete(DatabaseError databaseError, DatabaseReference reference) {
                if (databaseError != null) {
                    Log.e(TAG, "Failed to write message", databaseError.toException());
                }
            }
        });

the 'object' is created properly. There is no error I am getting and I have checked in debugging that the onComplete method is not getting triggered. Security Rule is also true for write.

Upvotes: 1

Views: 3830

Answers (2)

Shashwat Gupta
Shashwat Gupta

Reputation: 872

use the below code:

mFirebaseRef.push().setValue(object).addOnCompleteListener(new OnCompleteListener<Void>() 
{
                            @Override
                            public void onComplete(@NonNull Task<Void> task) {
                           if(task.isSuccessful()){
                               // write code for successfull operation
                           }
                            }
                        });
                    }

.push will generate a random key on which your data will stored if you do not use .push it will overwrite on previous stored data.

Upvotes: 0

Bob Snyder
Bob Snyder

Reputation: 38319

Note that DatabaseReference.CompletionListener fires "when an operation has been acknowledged by the Database servers". Is it possible you did not have a network connection at the time you ran your test? I copied your code and ran it successfully on a phone with object defined like this:

Object object = new String("Test");

I then enabled airplane mode, re-ran the code and observed the behavior you describe. The completion listener did not fire until I disabled airplane mode and a network connection was established.

Example code for checking the status of your network connection is provided in this documentation.

Upvotes: 3

Related Questions