How to remove one Item in the database of the fire base? - java

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());

Related

Firebase onDataChange() method is not entered [duplicate]

I am trying to retrieve data from Firebase, but I don't know how. I have the following data structure in Firebase [1]: https://i.stack.imgur.com/vN7Ge.png:
![enter image description here][1]
I can retrieve the category title(sleep, Stress Relief, and Relax), but don't know how to retrieve the author.
dataSnapshot.child("author").getValue(String.class)) ; doesn't work.
.
databaseReference = FirebaseDatabase.getInstance().getReference().child("Category");
}
public void getDataFromFirebase() {
List<ParentItem> parentItemsList = new ArrayList<>();
databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
String category = dataSnapshot.child("Category").getValue(String.class));
String author = dataSnapshot.child("author").getValue(String.class));
}
Log.d("TAG", "onDataChange: "+ parentItemsList);
}
UPDATE
now I have the following code to retrieve data, but onDataChange () is never reached.
list.add("Milena"); // this word shows in recyclerview
databaseReference = FirebaseDatabase.getInstance().getReference().child("Category");
databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
list.add("M");
for (DataSnapshot ds : dataSnapshot.getChildren()) {
String category = ds.child("Category").getValue(String.class);
list.add(category);
for (DataSnapshot data : dataSnapshot.getChildren()) {
author = data.child("author").getValue(String.class);
list.add(author);
}
}
}
firebase rules:
{
"rules": {
".read": "auth==true",
".write": "auth==true"
}
}
I have line list.add("Milena") to make sure the problem is with firebase, not the recycler view itself. Recycler view shows only the word "Milena". And I have line as the first line of OnDataChange method list.add("M"). The recycler view doesn't shows the letter.
I already added google-services.json file to my app and added this line to manifest <uses-permission android:name="android.permission.INTERNET"/>
Why I can't still retrieve data?
If you want get field author, you can more loop for dataSnapshot like this
for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
String category = dataSnapshot.child("Category").getValue(String.class));
for(DataSnapshot data : dataSnapshot.getChildren()) {
String author = data.child("author").getValue(String.class));
}
}
hope this can solve your problem :)
I think that the problem is your reference points to Category and you want the author. Between category and authors there are 2 children ("Sleep" and "1").
So, I think the best to do is change this line:
databaseReference = FirebaseDatabase.getInstance().getReference().child("Category");
in this:
databaseReference = FirebaseDatabase.getInstance().getReference().child("Category").child("Sleep").child("1");
To solve this issue you have to iterate through the children twice, as seen in the following lines of code:
DatabaseReference db = FirebaseDatabase.getInstance().getReference();
DatabaseReference categoryRef = db.child("Category");
categoryRef.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
#Override
public void onComplete(#NonNull Task<DataSnapshot> task) {
if (task.isSuccessful()) {
DataSnapshot snapshot = task.getResult();
for (DataSnapshot categorySnapshot : snapshot.getChildren()) {
String categoryName = categorySnapshot.getKey();
Log.d("TAG", categoryName);
for (DataSnapshot ds : categorySnapshot.getChildren()) {
String author = ds.child("author").getValue(String.class);
Log.d("TAG", author);
}
}
} else {
Log.d("TAG", task.getException().getMessage()); //Never ignore potential errors!
}
}
});
But be aware that a child as Category: "Sleep" should not exist on the same level as 1, 2, and so on. Since the name of the category already exists as the key of a node, please remove those records:
In this way, you'll avoid a ClassCastException, as at the same level you have an object with two properties and a String one. So once you remove those children, the above code will work perfectly fine. If you however need a node to contain that information, I recommend you create a top-level node that will contain only the name of the categories.

How can I iterate through Firebase table if it contains data from more app authenticated users?

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());

Issue with FirebaseDatabase and FirebaseFirestore Data Manupulate and Retriving data

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) {
}
});

Why does my firebase database child return null?

I am working with firebase database and i was trying to get the value of a child using this code below and may System.out.println(MyCredit.toString()); is always returns null: Please see my firebase database
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Users");
ref.addListenerForSingleValueEvent(
new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//Get map of users in datasnapshot
CollectCredits((Map<String,Object>) dataSnapshot.getValue());
}
#Override
public void onCancelled(DatabaseError databaseError) {
//handle databaseError
}
});
private void CollectCredits(Map<String,Object> users) {
MyCredit = 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 Credit field and append to list
MyCredit.add((Long) singleUser.get("Credit"));
Toast.makeText(MainActivityCustonlistViewnew.this, "Credit : " +String.valueOf(MyCredit), Toast.LENGTH_SHORT).show();
}
System.out.println(MyCredit.toString());
}
Try this:
private void CollectCredits(DataSnapshot dataSnapshot) {
MyCredit = new ArrayList<>();
//iterate through each dataSnapshot
for (DataSnapshot d1 : dataSnapshot.getChildren()){
MyCredit.add(d1.getValue());
}
}
Let me give you some suggestions, Try to check your firebase database path both the root and child path because some time you did everything correctly but the path you specified to your Database reference which is not referring to the correct path. So it can produce the same result what are getting right now.

Android Firebase Fetch Data Of Every User

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.

Categories