如何在 firebase 中添加新数据 android

How to add new data in firebase android

这是我在 firebase 实时数据库中添加新人的逻辑。但是它不是创建新条目,而是用新数据更新旧数据。

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());
        }
    });

这里有什么问题?谁能帮我解决这个问题?

您每次单击 buttonSave 时都在引用 "Person" 子项并设置它的值 (setValue()),这只会编辑那个子项。尝试改用 push()

您一直在使用 相同的参考

 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.

在你的情况下,你出于这个原因正在覆盖相同的数据

每次将新子添加到指定的 Firebase 引用时,您应该使用 push() 方法生成唯一 ID。

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

您可以向您的数据添加新的 Child,例如:

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);

登录用户不同时,userId也不同,因此,您总是会在Users下的userId中找到一个新的logged-in-user新的数据列表。

每次选择插入数据到数据库时调用下面的方法。 您可以集成尽可能多的属性,optate.It 每次都会生成一个唯一的键并插入记录。

 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);
}

它将在数据库层次结构中像这样

-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"