import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.IgnoreExtraProperties;
//Declaration of firebase references
private DatabaseReference mDatabase;
//Declaration of firebase atributtes
public String uID;
public String username;
public String email;
@IgnoreExtraProperties
public class User {
//Default constructor
public User() {
//Default constructor required for calls to DataSnapshot.getValue(User.class)
mDatabase = FirebaseDatabase.getInstance().getReference();
//...
}
//...
}
addListenerForSingleValueEvent()
to our database reference://Add new imports
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.ValueEventListener;
//...
public void getUser(String uID){
//The uID it's unique id generated by firebase database
mDatabase.child("users").child(uID).addListenerForSingleValueEvent(
new ValueEventListener () {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
// ...
}
@Override
public void onCancelled(DatabaseError databaseError) {
// Getting Post failed, log a message
}
});
}
onDataChange()
event: @Override
public void onDataChange(DataSnapshot dataSnapshot) {
//Inflate class with dataSnapShot
Users user = dataSnapshot.getValue(Users.class);
//...
}
//User inflated
Users user = dataSnapshot.getValue(Users.class);
//Get information
this.uID = user.uID;
this.username = user.username;
this.email = user.email;
Best practices
//Declaration of firebase references
//...
final private DatabaseReference userRef = mDatabase.child("users").child("premium").child("normal").getRef();
//...
public void getUser(String uID){
//Call our reference
userRef.child(uID).addListenerForSingleValueEvent(
new ValueEventListener () {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
// ...
}
@Override
public void onCancelled(DatabaseError databaseError) {
// Getting Post failed, log a message
}
});
}
onCancelled()
event is called when the user doesn't have access this reference by database rules. Add pertinent code to control this exception if you need.For more information visit official documentation