I'm developing an app with Android Studio using Firebase. I want to delete a certain date but when I click on the delete button it does nothing. I can't reach to parent because it's a generated key. Any help would be appreciated.
private void deleteDate(){
String dateValue = showDate.getText().toString();
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
String userid = user.getUid();
DatabaseReference usersRef = FirebaseDatabase.getInstance().getReference().child("Users").child(userid).child("smokeFreeDays");
usersRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull #NotNull DataSnapshot snapshot) {
for (DataSnapshot userDataSnapshot : snapshot.getChildren()) {
String date = userDataSnapshot.getValue(String.class);
if (date.equals(dateValue)) {
snapshot.getRef().child(dateValue).removeValue();
} else if (!date.equals(dateValue)) {
snapshot.getRef().child(dateValue).removeValue();
}
}
}
#Override
public void onCancelled(#NonNull #NotNull DatabaseError error) {
Log.w("tag", "loadPost:onCancelled", error.toException());
}
});
}
My Database:
See my comment above for debugging the issue.
But as an overall hint, I'd recommend reconsidering the data structure under smokeFreeDays to look like this:
"smokeFreeDays": {
"2021-05-09": true,
"2021-05-10": true
}
The two changes in this structure:
The date format is now ordered year-month-day, which is better suited for querying. For example, you can get all smoke free days in 2021 with: usersRef.orderByKey().startAt("2021-").endAt("2021~").
We now use the date as the key, which means we no longer have to load all smokeFreeDays to find the value to delete. You can now delete the node once you know the date with: usersRef.child("2021-05-09").removeValue().
Related
I am making an android app through android studio in java language. I have linked it to firebase Realtime database. There are auto generated push IDs as the last child. I want to retrieve my database values back in an activity. I am facing problem in giving reference to the push IDs.
This is what I have tried.
myRef = myfire.getReference().child("Data").child(strUID).child("Traffic").child("Wedding");
final String uid =myRef.getKey();
myRef.child(uid).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.getValue() == null) {
Toast.makeText(getApplicationContext(),"Data Not Available",Toast.LENGTH_LONG).show();
} else {
String stData1 = (Objects.requireNonNull(dataSnapshot.child("stData1").getValue())).toString();
String stData2 = (Objects.requireNonNull(dataSnapshot.child("stData2").getValue())).toString();
String stData3 = (Objects.requireNonNull(dataSnapshot.child("stData3").getValue())).toString();
String stData4 = (Objects.requireNonNull(dataSnapshot.child("stData4").getValue())).toString();
category basic = new category(stData1,stData2,stData3,stData4);
tvBalance.setText(stData4);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
Please provide a practical example.
Edit
This is my database structure:------------
Data>>
user id>>>>
Traffic>>>>
Wedding>>>>
Auto ID>>>
>stData1
>stData2
>stData3
>stData4 //I want to get this last value//
my json file
{
"Data" : {
"UyhzVqsz1BVFKoePa2NEmlPFu382" : {
"Traffic" : {
"Wedding" : {
"-MYKeSN8GZ8WbI-8TfVB" : {
"stData1" : "15 Apr 2021,06:43:00:pm",
"stData2" : "Wedding",
"stData3" : "kkk",
"stData4" : "100"
}
}
}
}
}
}
The only ways to get a node is by either knowing its full path, or by knowing the path to the parent node, and then some unique value under the node. Neither seems to be the case for the stData4 in your JSON, so you'll have to load the entire Wedding node and then loop over the results to get the part you want.
This isn't too bad though:
myRef = myfire.getReference("Data").child(strUID).child("Traffic/Wedding");
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (!dataSnapshot.exists()) {
Toast.makeText(getApplicationContext(),"Data Not Available",Toast.LENGTH_LONG).show();
} else {
for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
String stData1 = childSnapshot.child("stData1").getValue(String.class);
String stData2 = childSnapshot.child("stData2").getValue(String.class);
String stData3 = childSnapshot.child("stData3").getValue(String.class);
String stData4 = childSnapshot.child("stData4").getValue(String.class);
}
category basic = new category(stData1,stData2,stData3,stData4);
tvBalance.setText(stData4);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
The code above assumes that:
strUID has the value UyhzVqsz1BVFKoePa2NEmlPFu382
I am trying to make a message section in my app.
Model Description:
You can ignore DUYURU, it isn't related with topic.
child of DUYURU means author's uid.
Number represents messages unique index.
Model
My java-android code:
mRef = FirebaseDatabase.getInstance().getReference("Tests").child("DUYURU");
mRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
posts.clear();
for (DataSnapshot userMessages:snapshot.getChildren()) {
//These 2 values become null since childs are not exist
String sender = userMessages.child("sender").getValue(String.class);
String photoUri = userMessages.child("photoUri").getValue(String.class);
String uid = userMessages.getKey();
for (DataSnapshot dataSnapshot: userMessages.getChildren()) {
Post post = dataSnapshot.getValue(Post.class);
post.setPostInfo(sender,photoUri,uid);
post.setIndex(Integer.parseInt(dataSnapshot.getKey()));
posts.add(post);
}
}
Collections.sort(posts,Collections.<Post>reverseOrder());
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Log.e(TAG, "onCancelled: ",error.toException() );
}
});
Then sender's value becomes null since there is no child called sender.
So how can i create a child if not exists while messages are retrieving.
//checking if object is not exist in for loop
if (!userMessages.hasChild("sender")) {
mRef.child(userMessages.getKey()).child("sender").setValue("sendername");
}
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());
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) {
}
});
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.