- Mastering Firebase for Android Development
- Ashok Kumar S
- 189字
- 2021-06-18 18:49:11
Writing into Realtime Database
Fetch an instance of your database employing getInstance() and reference the location you need to write. You can write most of the primitive data types as they also include Java objects:
// Write a message to the database
FirebaseDatabase mDatabase = FirebaseDatabase.getInstance();
DatabaseReference mDbRef = mDatabase.getReference("Donor/Name");
mDbRef.setValue("Parinitha Krishna");
The following screenshot explains the dashboard changes after running the preceding code:
If you notice that there aren't any changes in the dashboard from the write operation, we shall attach an onFailure callback like the following for identifying what's stopping it:
// Write a message to the database
FirebaseDatabase mDatabase = FirebaseDatabase.getInstance();
DatabaseReference mDbRef = mDatabase.getReference("Donor/Name");
mDbRef.setValue("Parinitha Krishna").addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.d(TAG, e.getLocalizedMessage());
}
});
Before we compile the preceding code snippet, we need to change the rules to be true since we are no longer using any authentication service. Go to the Rules tab and change the read and write service to be true. When we do this, remember that the endpoint is publicly accessible by anybody who has the URL:
{
"rules": {
".read": true,
".write": true
}
}