I want to hide a Button
in my app when the user that is logged in has a specified value in the Realtime Firebase Database.
So I have a child where the value changes between Yes or No it depends on what rights the user is having. So I want to hide a Button
when a user has the value No and when the user has the value Yes, it will be available.
My Firebase database structure is like this: (the child "hasusersstorage" is the Yes or No (Ja/Nei) Firebase structure
Here is the code I've tried but not managed to get it to work.
The currentUser
is working, because I use this to setText with a username that is logged in.
databaseUsers.child(currentUser).child("hasuserstorage").equalTo("Nei").addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
if (dataSnapshot.hasChild("hasuserstorage")) {
bttoaddtool.setVisibility(View.GONE);
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
Hope someone can help me out.
CodePudding user response:
I want to hide a Button in my app when the user that is logged in has a specified value in the Firebase database.
If you want to achieve that, then you should create a reference that points exactly to the hasuserstorage
field.
When you are using the following code query:
databaseUsers.child(currentUser).child("hasuserstorage").equalTo("Nei");
It doesn't mean that you are checking if the hasuserstorage
field of the logged-in user holds the value of Nei
. Assuming that Ansatte
is a direct child of your root node, to solve this, please use the following lines of code:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference db = FirebaseDatabase.getInstance().getReference();
DatabaseReference hasUserStorageRef = db.child("Ansatte").child(uid).child("hasuserstorage");
hasUserStorageRef.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
@Override
public void onComplete(@NonNull Task<DataSnapshot> task) {
if (task.isSuccessful()) {
DataSnapshot snapshot = task.getResult();
if(snapshot.exists()) {
String hasuserstorage = snapshot.getValue(String.class);
if(hasuserstorage.equals("Ja")) {
Log.d("TAG", "hasuserstorage is Ja");
bttoaddtool.setVisibility(View.VISIBLE);
} else if(hasuserstorage.equals("Nei")) {
Log.d("TAG", "hasuserstorage is Nei");
bttoaddtool.setVisibility(View.GONE);
}
}
} else {
Log.d("TAG", task.getException().getMessage()); //Never ignore potential errors!
}
}
});
The above code will hide the button if the hasuserstorage
will hold the value of Nei
, otherwise it will display it.