Setting custom key when pushing new data to firebase database

后端 未结 10 571
野的像风
野的像风 2020-12-13 12:22

Well, I am new to Firebase and I want to have my own keys while pushing new data to database.

Problem:

FireBase.push().setValue(mapped_values);


        
相关标签:
10条回答
  • 2020-12-13 12:55

    Simple and Fast

     Map<String,Object> taskMap = new HashMap<>();
           taskMap.put("Name", name.getText().toString());
           taskMap.put("km", km.getText().toString());
          // taskMap.put("age", "45");
           taskMap.put("Day", day.getText().toString());
           mDatabaseReference.push().setValue(taskMap);
    
    0 讨论(0)
  • 2020-12-13 13:00
            String key="1234567sdfsf8";
            //custom object
            User user=new User();
            DatabaseReference mDatabase;
            mDatabase = FirebaseDatabase.getInstance().getReference();
            mDatabase.child("Users").child(key).setValue(user);
    
    0 讨论(0)
  • 2020-12-13 13:03

    You can create a custom key using setValue() even if the root contains many children for example if 'Users' is the root and you want to add users with email as a key it will be like this

    firebase.child("firebase url").child("Users").child("user_1 email").setValue(...)
    
    firebase.child("firebase url").child("Users").child("user_2 email").setValue(...)
    

    etc

    Hope this helps.

    0 讨论(0)
  • 2020-12-13 13:05

    Calling push() will generate a key for you.

    If instead you use child(), you can determine they key/path yourself.

    ref.child("Victor").setValue("setting custom key when pushing new data to firebase database");
    
    0 讨论(0)
  • 2020-12-13 13:12

    If you are using FirebaseUI :

    private static final CollectionReference usersCollection = FirebaseFirestore.getInstance().collection("users");
    
    User user = new User("MyUsername", "MyPictureUrl");
    String userKey = "1234567sdfsf8";
    
    usersCollection.document(userKey).set(user); //MAGIC LINE
    
    0 讨论(0)
  • 2020-12-13 13:13

    As an update to the top answer, the Firebase API has been changed and setValue() does not work anymore. Now you must use the set() function instead:

    ref.child("Victor").set("setting custom key when pushing new data to firebase database");
    
    0 讨论(0)
提交回复
热议问题