I am having a problem retrieve and delete the correct level of the node in Firebase database using the orderByChild().equalTo() method.
Searched over the web for quite a while and didn't really solve my problem. Please help.
My database structure:
My Firebase methods to add and delete photo
private void addPhotoToDatabase(String url){
Log.d(TAG, "addPhotoToDatabase: adding photo to database");
String newPhotoKey = myRef.child(mContext.getString(R.string.dbname_user_photos)).push().getKey();
Photo photo = new Photo();
photo.setDate_created(getTimeStamped());
photo.setImage_path(url);
photo.setUser_id(FirebaseAuth.getInstance().getCurrentUser().getUid());
photo.setPhoto_id(newPhotoKey);
//insert into database.
myRef.child(mContext.getString(R.string.dbname_user_photos)).child(FirebaseAuth.getInstance().getCurrentUser().getUid()).child(newPhotoKey).setValue(photo);
}
private void deletePhotoFromDatabase(String image_path){
Log.d(TAG, "deletePhotoFromDatabase: deleting photo from database");
Log.d(TAG, "deletePhotoFromDatabase: image_path is " + image_path);
String user_id = FirebaseAuth.getInstance().getCurrentUser().getUid();
myRef.child(mContext.getString(R.string.dbname_user_photos))
.child(user_id)
.orderByValue().equalTo(image_path).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String photoKey = dataSnapshot.getKey();
Log.d(TAG, "onDataChange: photo key is " + photoKey);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
I know I don't have a removeValue or setValue(null) method yet because I just can't get to the correct level. The photoKey I was trying to retrieve is the -L-FnLvNxLauiue4InSxE which was automatically generated when adding into Firebase. However, the log always returns to its parent node which is the UID.
By the way, the image_path I retrieved from the Firebase storage which was logged correctly.
Could someone give me some inspirations where I did wrong? Thanks a lot!
change this:
myRef.child(mContext.getString(R.string.dbname_user_photos))
.child(user_id)
.orderByValue().equalTo(image_path)
to this:
DatabaseReference myRef=FirebaseDatabase.getInstance().getReference();
myRef.child("user_photos").child(user_id).orderByChild("photo_id").equalTo(image_path);
Im assuming user_photos is a direct child under root, thus using the above myRef
Edit:
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot data : dataSnaphot.getChildren()){
String photoKey = data.getKey();
Log.d(TAG, "onDataChange: photo key is " + photoKey);
} }
Related
Here is my Firebase Realtime Database schema. I want to get passwords and usernames from all employees.
Is there a way to get a specific value of a child in the Realtime Database?
To actually get the user names and passwords from all employees, you have to create a reference that points to the "Employs" node, perform a get() call and attach a listener. So please use the following lines of code:
DatabaseReference db = FirebaseDatabase.getInstance().getReference();
DatabaseReference employsRef = db.child("Admin").child("Employs");
employsRef.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
#Override
public void onComplete(#NonNull Task<DataSnapshot> task) {
if (task.isSuccessful()) {
for (DataSnapshot ds : task.getResult().getChildren()) {
String name = ds.child("name").getValue(String.class);
String password = ds.child("name").getValue(String.class);
Log.d("TAG", name + "/" + password);
}
} else {
Log.d("TAG", task.getException().getMessage()); //Don't ignore potential errors!
}
}
});
The result in the logcat will be:
usman/88568558458
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).
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) {
}
});
i have a problem in my android project which is connected to firebase. I want to display the child elements of my firebase database in a recyclerview. For this i created the following code to save the data in an arraylist. But there is a problem with attaching the childs of the path - the code does not add the items to the list :|. Is there an error in the reference to the database or an error in the eventlistener?
private void loadDataOutfitDetail(String userID, String weatherToday){
// set the firebase path for loading the images of the clothes
databaseRefOutfit = FirebaseDatabase.getInstance().getReference(userID + "/" + weather1 + "/ID1" + "/details");
// clear the list for showing only the filtered weather
uploadDetails.clear();
// get data out
databaseRefOutfit.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()){
UploadDetails upload = postSnapshot.getValue(UploadDetails.class);
// add items to list
uploadDetails.add(upload);
}
// update the recyclerview
outfitAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(getActivity(), databaseError.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
My Firebase database has the following structure:
USERID
outfit
weather1
ID1
details
desciption: Here is a description
name: MyName
imageUpperPart
name: image1
ID2
details
description: Here is another description
name: NewName
imageUpperPart
name: image2
How can I add the values of the details node to the arraylist uploadDetails?
Thank you keved :)
Change the reference to the following:
DatabaseReference ref = FirebaseDatabase.getInstance().getReference(userID).child("outfit").child("weather1").child("ID1").child("details");
You are missing the node outfit in your reference.
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.