Data not getting saved in Firebase database from android

柔情痞子 提交于 2020-01-06 16:18:33

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/37470219/data-not-getting-saved-in-firebase-database-from-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!