Issue
I want to get data from the Firebase Realtime Database.
I'm trying to access the value of "creator" by giving the user's Email.
For example:
For the input cc@cc@cc I will get false.
For the input tt@tt@tt I will get true.
Here is my code:
String key = emailEditText.getText().toString().replace(".","@");
myRef.child("Users").child(key).child("creator").addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
try {
for (DataSnapshot postsnapshot : snapshot.getChildren()) {
if(postsnapshot.getValue().equals(true)){
startActivity(new Intent(LoginActivity.this,CreatorActivity.class));
}
else
startActivity(new Intent(LoginActivity.this,WelcomeActivity.class));
}
*Key is the Input Email.
Solution
String email = "[email protected]";
DatabaseReference db = FirebaseDatabase.getInstance().getReference();
DatabaseReference usersRef = db.child("Users");
Query queryByEmail = usersRef.orderByChild("email").equalTo(email);
queryByEmail.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
@Override
public void onComplete(@NonNull Task<DataSnapshot> task) {
if (task.isSuccessful()) {
for (DataSnapshot ds : task.getResult().getChildren()) {
boolean creator = ds.child("creator").getValue(Boolean.class);
Log.d("TAG", "creator: " + creator);
}
} else {
Log.d("TAG", task.getException().getMessage()); //Don't ignore potential errors!
}
}
});
The result in the logcat will be:
creator: false
However, if you change the email to:
String email = "[email protected]";
The result in the logcat will be:
creator: true
This solution will work for multiple nodes in your database. If you only want to check a single one, then please use the following line of code:
String email = "cc@cc@cc";
DatabaseReference db = FirebaseDatabase.getInstance().getReference();
DatabaseReference creatorRef = db.child("Users").child(email).child("creator");
creatorRef.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
@Override
public void onComplete(@NonNull Task<DataSnapshot> task) {
if (task.isSuccessful()) {
DataSnapshot snapshot = task.getResult()
boolean creator = snapshot.getValue(Boolean.class);
Log.d("TAG", "creator: " + creator);
} else {
Log.d("TAG", task.getException().getMessage()); //Don't ignore potential errors!
}
}
});
The result in the logcat will be:
creator: false
However, if you change the email to:
String email = "tt@tt@tt";
The result in the logcat will be:
creator: true
Answered By - Alex Mamo
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.