After you have set a few data to database and have get a structure consisting of several nodes like this;
"user" : {
"-KdbKcU2ptfYF2xKb5aO" : {
"firstName" : "Arthur",
"lastName" : "Schopenhauer",
"userName" : "AphorismMan",
"phone" : "+9022-02-1778",
"gender": "M",
"age" : 25
},
"-KdbQFjs9BDviuqQVHjY" : {
"firstName" : "Werner",
"lastName" : "Heisenberg",
"userName" : "whereAmI",
"phone" : "+9005-12-1901",
"gender": "M",
"age" : 75
}
}
you can categorize data structures.
Creating Class
Create a model class to set to database.
@IgnoreExtraProperties
public class User {
public String firstName;
public String lastName;
public String userName;
public String phone;
public String gender;
public int age;
public User() {
}
public User(String firstName, String lastName, String userName, String phone, String gender, int age) {
this.firstName = firstName;
this.lastName = lastName;
this.userName = userName;
this.phone = phone;
this.gender = gender;
this.age = age;
}
}
Some things to remember when creating a model class that you want to map to your data:
Sending to Firebase
Create a User object
User user = new User ( "Arthur","Schopenhauer","AphorismMan","+9022-02-1778","M",25)
and reference
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference();
Now you have the reference of your database. Create an user
node with databaseReference.child("user")
. If you do .push()
your models will locate under randomly created unique ids like above, "-KdbKcU2ptfYF2xKb5aO", "-KdbQFjs9BDviuqQVHjY"
.
databaseReference.child("user").push().setValue(user, new DatabaseReference.CompletionListener() {
@Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
Toast.makeText(getActivity(), "User added.", Toast.LENGTH_SHORT).show();
}
});
If you want to set your datas under your specific key, do it with .child("yourSpecificKey")
instead of .push()
.
databaseReference.child("user").child("yourSpecificKey").setValue(user,...