user3559471
user3559471

Reputation: 583

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?

Upvotes: 18

Views: 62144

Answers (4)

MDNSRF
MDNSRF

Reputation: 31

every time when you optate to insert data to database call the follwing method. You can integrate as many attributes you optate.It will engender a unique key everytime and insert records.

 public void insert2database(double latitude,double longitude,String name) {

    HashMap<String,String> student=new HashMap<>();
    
    student.put("Name",name);
    student.put("Lat", String.valueOf(latitude));  
    student.put("Long", String.valueOf(longitude));   
    student.put("Phone", String.valueOf("78787500000")); 
    
    DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
    DatabaseReference tasksRef = rootRef.child("USERS").push();
    tasksRef.setValue(student);
}

It will be in the database hierarchy like this

-database-4df17-default-rtdb
   -USERS
      -MUqgUu8zUpYcIaUVSsj
        -Lat:  "25.9405145"
        -Long: "79.9100086"
        -Name:"Dilroop"
        -Phone: "78787500000"
      -MUqoL2AUQFjH2ggKWev
        -Lat: "32.9405145"
        -Long: "73.9178186"
        -Name: "Sanghavi"
        -Phone: "78787500000"
      -MUsfc-H-7KdQhrkHb_F
        -Lat: "52.9405145"
        -Long: "79.9175856"
        -Name: "MDNSRF"
        -Phone: "78787500000"

Upvotes: 2

Gabriele Mariotti
Gabriele Mariotti

Reputation: 364978

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);
 DatabaseReference newRef = ref.child("Person").push();
 newRef.setValue(person);

Upvotes: 38

Loyal Fine
Loyal Fine

Reputation: 113

You can add a new Child to your data, such as:

mAuth = FirebaseAuth.getInstance();
FirebaseUser user = mAuth.getCurrentUser();
String userId = user.getUid();
Firebase rootRef = new Firebase(Config.USER_URL);
Firebase userRef = rootRef.child("Users");
Person newUser = new Person();
newUser.setFirstName(firstName);
newUser.setLastName(lastName);
userRef.child(userId).setValue(newUser);

The userId varies when the logging user is different, therefore, you will always go to a new data list for a new logged-in-user in the userId under Users.

Upvotes: 1

AL.
AL.

Reputation: 37798

You are referencing to the "Person" child and setting it's value (setValue()) every time you click buttonSave, which only edits that one child. Try to use push() instead.

Upvotes: 0

Related Questions