For example, there are 2 main nodes in my database (there can be more). The parent node is the user's authentication id and inside it
there is some detail as you can see.
I am trying to do that if any user login all other user's data populated on his activity
but I really don't know how to start because every user has its own authentication id and there are sub-nodes also like map location and image
How can I fetch every user's detail to the activity?
What you can do is that get the data from the fbuserinfo node using an event listener like this and iterate through the data. Here User.class is the class for the User model that you have created
DatabaseReference userDataReference = FirebaseDatabase.getInstance().getReference()
.child("fbuserinfo");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
User user = ds.getValue(User.class);
Log.d("User", user);
}
}
}
#Override
public void onCancelled (DatabaseError databaseError){
Log.d(TAG, "Error fetching user data - " + databaseError.getMessage());
}
}
userDataReference.addListenerForSingleValueEvent(eventListener);
And then if you want to display the data, you can do it in the for loop and have an if condition to check if the user is not equal to the current one
Using the following example you'll be able to log the name of all users from your database.
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference fbRef = rootRef.child("Users").child("fbusersinfo");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String name = ds.child("name").getValue(String.class);
Log.d("TAG", name);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
fbRef.addListenerForSingleValueEvent(eventListener);
The output will be:
Ahmend Abbas
mahanoor 4
If you need also the other properties, you can get them in the same manner.
Related
What is the proper way to read data from Firebase Realtime Database? I have created a database "Mybill"s with child bills. In child Bills, I am saving UserId from FirebaseAuth so it should be easy to find bills for a specific user and in userID child, I have a child that I have created using the .push() method and in that, I have data about the bill.
It looks like this:
How should I change my Java code so I can get all the bills saved for a specific user (the user that is currently logged in)
this is my code for now :
final FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference ref = database.getReference("bills");
Query checkUser = ref.orderByChild("UserId").equalTo(Autentication.GetUser());
// Attach a listener to read the data at our posts reference
checkUser.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String email = dataSnapshot.child("email").getValue(String.class);
String market = dataSnapshot.child("market").getValue(String.class);
String price = dataSnapshot.child("price").getValue(String.class);
String date = dataSnapshot.child("date").getValue(String.class);
}
#Override
public void onCancelled(DatabaseError databaseError) {
System.out.println("The read failed: " + databaseError.getCode());
}
});
How should I change my Java code so I can get all the bills saved for a specific user (the user that is currently logged in)
To do that, please use the following lines of code:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidRef = rootRef.child("bills").child(uid);
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String email = ds .child("email").getValue(String.class);
String market = ds .child("market").getValue(String.class);
String price = ds .child("price").getValue(String.class);
Log.d("TAG", email + "/" + market + "/" + price);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d("TAG", databaseError.getMessage()); //Don't ignore potential errors!
}
};
uidRef.addListenerForSingleValueEvent(valueEventListener);
The "date" cannot be read as a String, as it's an object. So the most appropriate way would be to read it as a Map<String, Object>. In this way, you are getting only the bills that correspond to a specific user (logged-in user).
I'm developing a travel Android app and the idea is that a user can authenticate and create a personal account through Firebase Authentication. One of the functionalities says that every user can post reviews. Now, what I want is to retrieve all the reviews from the Firebase Realtime Database (not just the current user reviews, all of them). How could I achieve this?
To get all the reviews that correspond to all users, you have to iterate twice, like in the following lines of code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference reviewsRef = rootRef.child("reviews");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot uidSnapshot : dataSnapshot.getChildren()) {
for(DataSnapshot reviewSnapshot : uidSnapshot.getChildren()) {
String comment = reviewSnapshot.child("comment").getValue(String.class);
Log.d("TAG", comment);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d("TAG", databaseError.getMessage()); //Don't ignore errors!
}
};
reviewsRef.addListenerForSingleValueEvent(valueEventListener);
The output in the logcat will be:
Really nice place
The ideal place for holiday. No matter if it
Hi
If you are using a POJO class for your review object, then please use:
Review review = reviewSnapshot.getValue(Review.class);
Log.d("TAG", review.getComment());
How to remove one Item in the database of the fire base?
I have code to delete the entire database:
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
Query applesQuery = ref.child("Markers").orderByChild(firebaseAuth.getUid());
applesQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot appleSnapshot : dataSnapshot.getChildren()) {
appleSnapshot.getRef().removeValue();
}}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.e(TAG, "onCancelled", databaseError.toException());
}
});
the picture shows that in the Marker database there are 2 entries and they have folded entries !!! How to delete one entry (logged in user), and the second should remain in the database ???
As those keys are user id's you can do the following
FirebaseDatabase.getInstance().getReference()
.child("Markers")
.child(firebaseAuth.getUid())
.removeVaule();
It will delete that node and folded data too
Change the query to the following :
Query appQuery = ref.child("Markers").orderByKey().equalTo(firebaseAuth.getUid());
My query is that I want to save some data in Firebase Realtime Database such that I will be able to call the data. Keeping in mind that users should be able to call the data even if they reinstall the app and each user will have a specific child.
I am trying to make an app where the user will enter or save data to firebase and display it on the App, however, the issue is that I am not having an Idea on how to retrieve the data from firebase.
The data which I am going to retrieve is the ItemName which I have saved inside
child(uid).child(ItemName);
each user will save their data with different uid inside different ItemName.
The thing is that how will I retrieve the ItemName for each user since the ItemName will be different so I will not have any data of the ItemName for a particular user. If I save the ItemName in SharedPreferences I will be able to retrieve it, however, if the user, formate their phone or uninstall and reinstall the app then SharedPreference data will be removed, SO HOW WILL I RETRIVE THE ITEMNAME data from Firebase for a particular user to display it.
MY CODE example:
String email= mAuth.getCurrentUser().getUid();
dbFirestore= FirebaseFirestore.getInstance();
userReference= FirebaseDatabase.getInstance().getReference().child("Users").child(itemName);
Is there any method or function which retrieve the data without specifying the Child pathname like default path if we redirect the path towards there like
databaseReference = FirebaseDatabase.getInstance().getReference().child(uid).child("");
something like that. or is there any other way to do it.
To those values, without knowing the name of the intermediate node, please use the following lines of code:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidRef = rootRef.child(uid);
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String friedChicken = ds.getKey();
String foodType = ds.child("food_TYPE").getValue(String.class);
Log.d("TAG", friedChicken + "/" + foodType);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d("TAG", databaseError.getMessage()); //Don't ignore errors!
}
};
uidRef.addListenerForSingleValueEvent(valueEventListener);
The output in the logcat will be:
Fried Chicken / Non-Veg
In the same way I got the value of food_TYPE, you can also get the others.
You can do the following
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child(uid).child("Fried Chicken");
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String foodType = dataSnapshot.child("food_TYPE").getValue().toString();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
so i am stuck. i want to retrieve child of child from my firebase database.
my database struture looks like this
users{
user1{
name:
regno:
carmodel:
caryear}
user2{
name:
regno:
carmodel:
caryear}
user3{
name:
regno:
carmodel:
caryear}}
Regno = car registration number.
when i type in a "carreg no" and press ok. i want the code to search every carreg. if a match is found execute next set of codes.
so far i have tried to store it in a array. but the code seems to fail when i put reg or any variable name that exist.
public void input(){
FirebaseDatabase firebase = FirebaseDatabase.getInstance();
final DatabaseReference table_user = firebase.getReference("User");
table_user.addListenerForSingleValueEvent(
new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//Get map of users in datasnapshot
collectPhoneNumbers((Map<String,Object>) dataSnapshot.getValue());
}
#Override
public void onCancelled(DatabaseError databaseError) {
//handle databaseError
}
});
private void collectPhoneNumbers(Map<String,Object> users) {
ArrayList<Long> phoneNumbers = new ArrayList<>();
//iterate through each user, ignoring their UID
for (Map.Entry<String, Object> entry : users.entrySet()){
//Get user map
Map singleUser = (Map) entry.getValue();
//Get phone field and append to list
phoneNumbers.add((Long) singleUser.get("namesd"));
}
System.out.println(phoneNumbers.toString());
mVoiceInputTv.setText("" + phoneNumbers);
}
}
i got this from another stackflow. before this i tried creating a for look. it was successfull but result failed 80% of the time. (not always correct).
To solve this, you need to query your database using orderByChild() method like this:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference usersRef = rootRef.child("users");
Query regnoQuery = usersRef.orderByChild("regno").equalsTo(regno);
In which regno argument from equalsTo() is the the actual registration number that you are looking for. Then attach a listener to the regnoQuery and use getChildrenCount() method on the dataSnapshot object. If the number of childrens is noOfChildrens > 0 then execute the set of codes you need.
private FirebaseDatabase mdatabase;
private DatabaseReference mdatabaseRef;
mdatabase = FirebaseDatabase.getInstance();
mdatabaseRef = mdatabase.getReference();
mdatabaseRef.child("users").child("users1").orderByChild("regno").equalsTo(regno).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot childSnapshot : dataSnapshot.getChildren()) {
}
}