Reputation: 75
I'm starting with programming, and I have questions. First, I can insert data on firebase, but, when I try to insert new data, this data inserted before is changed/updated to new data. How can I insert new data and continue with before data? Second, how can I insert data on firebase together "primary key"? (example in image). "Primary key" highlighted in image Hugs.
Upvotes: 0
Views: 3118
Reputation: 138804
A Firebase database is structured as pairs, of key and values. This means that every node in the database is a Map
. When you add data to Firebase, think that you are adding data to a Map
. As we know, a Map
does not allow duplicate keys. This means that if we use the same key, in the case of Map
, it replaces the old value with the new one. This means that every time we want to add data, we need a different key. The practice in Firebase is to use the push()
method, which provides a unique key every time the method is called.
To add data to your Firebase database, i recomand you using the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference tasksRef = rootRef.child("tasks").push();
tasksRef.setValue(taskObject);
You can also add CompletionListener
to actually see if the data was successfully added into the database.
Upvotes: 1
Reputation: 288
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference();
mDatabase.child("tasks").push().setValue(firebaseData, new DatabaseReference.CompletionListener() {
@Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
//Problem with saving the data
if (databaseError != null) {
} else {
//Data uploaded successfully on the server
}
}
});
Upvotes: 1