Writing Data to Firebase (Cont.)


For example, if you have an app with a basic user profile, your User object might look as follows:

 @IgnoreExtraProperties
 public class User {
   public String username;
   public String email;
   // Default constructor required for calls to DataSnapshot.getValue( User.class )
   public User( ) {  }
   public User( String username, String email ) {
     this.username = username;
     this.email    = email;
   }
 }

As every user needs a unique ID, you can generate one by calling push() method which creates an empty node with unique key. Then get the reference to “users” node using child() method. Finally use setValue() method to store the user data.

 DatabaseReference mDatabase = FirebaseDatabase.getInstance( ).getReference( "users" );
 // Creating new user node, which returns the unique key value
 // new user node would be /users/$userid/
 String userId = mDatabase.push( ).getKey( );
 // creating user object
 User user = new User( "Poke Mon", "poke@gmail.com" );
 // pushing user to 'users' node using the userID
 mDatabase.child( userID ).setValue( user );

Using setValue() in this way overwrites data at the specified location, including any child nodes. However, you can still update a child without rewriting the entire object. If you want to allow users to update their profiles you could update the username as follows:

 mDatabase.child( "users" ).child( userId ).child( "username" ).setValue( name );




      Q: What did the water say to the boat?    
      A: Nothing, it just waved.