user3559471 user3559471 - 2 months ago 45
Android Question

How to add new data in firebase android

This is my logic for adding new person in firebase realtime databse. But instead of making a new entry it is just updating the old data with new one.

buttonSave.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {


/*
new Firebase(Config.FIREBASE_URL)
.push()
.child("title")
.setValue(text.getText().toString());
*/

Firebase ref = new Firebase(Config.FIREBASE_URL);
String name = editTextName.getText().toString().trim();
String address = editTextAddress.getText().toString().trim();

//Creating Person object
Person person = new Person();

//Adding values
person.setName(name);
person.setAddress(address);
ref.child("Person").setValue(person);

}
});


new Firebase(Config.FIREBASE_URL).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
for (DataSnapshot postSnapshot : snapshot.getChildren()) {
//Getting the data from snapshot
Person person = postSnapshot.getValue(Person.class);

//Adding it to a string
String string = "Name: "+person.getName()+"\nAddress: "+person.getAddress()+"\n\n";

//Displaying it on textview
textViewPersons.setText(string);
}
}

@Override
public void onCancelled(FirebaseError firebaseError) {
System.out.println("The read failed: " + firebaseError.getMessage());
}
});


What is wrong here? Can anyone help me on this?

Answer

You are using always the same ref

 Person person = new Person();
 //Adding values
 person.setName(name);
 person.setAddress(address);
 ref.child("Person").setValue(person);

Check the doc:

Using setValue() in this way overwrites data at the specified location, including any child nodes.

In your case you are overriding the same data for this reason.

You should use the push() method to generate a unique ID every time a new child is added to the specified Firebase reference.

 Person person = new Person();
 //Adding values
 person.setName(name);
 person.setAddress(address);
 Firebase newRef = ref.child("Person").push();
 newRef.setValue(person);