I want to delete this node.
reference = FirebaseDatabase.getInstance().getReference("GroupDetails").child(firebaseUser.getUid()).child("groupMembers").child(chatModel.getId()).removeValue();
This above code I am using.
According to your comment:
I want to delete the value according to the Id that is given.
To solve this, you need to loop through the groupMembers node to get the corresponding child, call getRef(), and remove it.
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference groupMembersRef = rootRef.child("GroupDetails").child(uid).child("groupMembers");
groupMembersRef.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
#Override
public void onComplete(#NonNull Task<DataSnapshot> task) {
if (task.isSuccessful()) {
for (DataSnapshot ds : task.getResult().getChildren()) {
String value = ds.getValue(String.class);
if(value.equals(chatModel.getId())) {
ds.getRef().removeValue().addOnCompleteListener(/* ... */);
}
}
} else {
Log.d(TAG, task.getException().getMessage());
}
}
});
The result of the above code will be the removal of the second child.
Be sure to have the latest version of the Firebase Realtime Database SDK, as get() was recently added.
To remove data:
firebase.child(id).removeValue();
You might do well to have a look at the Firebase documentation for Android btw, which covers this and many more topics.
Related
I have a database structure as below.
I am able to retrieve the children's data when I give reference to date but I want to retrieve data without referencing to date but the previous nested key.
That is, when I write the following, I am able to get the data:
databaseReference = FirebaseDatabase.getInstance().getReference("LDC Wise").child("Agra").child("25-10-2022");
But when I write the following, I am getting null data:
databaseReference = FirebaseDatabase.getInstance().getReference("LDC Wise").child("Agra")
How do I go about fetching all the data in the next sublevel of the database without referencing to date key explicitly?
How do I go about fetching all the data in the next sublevel of the database without referencing to date key explicitly?
This can be solved by looping through the results twice:
DatabaseReference db = FirebaseDatabase.getInstance().getReference();
DatabaseReference agraRef = db.child("LDC Wise").child("Agra");
agraRef.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
#Override
public void onComplete(#NonNull Task<DataSnapshot> task) {
if (task.isSuccessful()) {
for (DataSnapshot snapshot : task.getResult().getChildren()) {
for (DataSnapshot innerSnapshot : snapshot.getChildren()) {
//Get the data out of the innerSnapshot object.
}
}
} else {
Log.d("TAG", task.getException().getMessage()); //Never ignore potential errors!
}
}
});
I want to delete this record ?
Because I don't know what exactly it is, I want to know what it is... I expect that it is a special key for every data I upload it creates it automatically How do I delete and what is this key?
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("poll_post").child(firebaseUser.getUid());
HashMap<String, Object> hashMap = new HashMap<>();
String postid = reference.push().getKey();
hashMap.put("postid", postid);
hashMap.put("time_post", ServerValue.TIMESTAMP);
hashMap.put("stopcomment", checked);
hashMap.put("tv_question", addcomment.getText().toString());
hashMap.put("tvoption1", Answer1.getText().toString());
hashMap.put("tvoption2", Answer2.getText().toString());
hashMap.put("vote1","0");
hashMap.put("vote2", "0");
hashMap.put("publisher", FirebaseAuth.getInstance().getCurrentUser().getUid());
reference.push().setValue(hashMap, new DatabaseReference.CompletionListener() {
#Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
//Problem with saving the data
if (databaseError != null) {
Toast.makeText(Write_poll.this, "Error", Toast.LENGTH_SHORT).show();
myLoadingButton.showErrorButton();
} else {
myLoadingButton.showDoneButton();
finish();
}
}
});
refer to firebase documentation and read about the function called push , they clearly said that
push : Add to a list of data in the database. Every time you push a new node onto a list, your database generates a unique key, like messages/users//
so that's means that every time you are pushing to the database , a new record with a unique ID will be generated every you push and you will not be able to override a record using the function push as every time it's called , it will generate a unique ID that you don' want in your case.
to avoid that , instead of
reference.push().setValue(hashMap, new DatabaseReference.CompletionListener(){ . . . }
write :
reference.setValue(hashMap, new DatabaseReference.CompletionListener(){ . . . }
If you want to delete a record from the Realtime Database, you have to create a reference that points to that node. In your particular case it would be:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference db = FirebaseDatabase.getInstance().getReference();
db.child("poll_post").child("-NBcO...y8cX").removeValue();
If you don't know the key, then you have to create a query to find that post based on something that uniquely identifies it, for example, the time_post. So here is the code:
DatabaseReference db = FirebaseDatabase.getInstance().getReference();
Query queryByTime = db.child("poll_post").orderByChild("time_post").equalTo(1662830174410);
queryByTime.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
#Override
public void onComplete(#NonNull Task<DataSnapshot> task) {
if (task.isSuccessful()) {
for (DataSnapshot ds : task.getResult().getChildren()) {
ds.getRef().removeValue();
}
} else {
Log.d("TAG", task.getException().getMessage()); //Never ignore potential errors!
}
}
});
You can also attach a listener to the removeValue() operation to see if something goes wrong.
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.
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
How can we access all UID users name and the UID users child value in Firebase database?
I have uploaded the pic of my database
I also use RecyclerView you tell me about Firebase query I want to retrieve data with FirestoreRecyclerOptions query :
I want to access
name of users and the amount value as shown in fig
like this
name:600
To get all user names, of all User objects that exist under "Users" node, please use the following lines of code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference usersRef = rootRef.child("Users");
productsRef.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);
Log.d(TAG, name);
}
} else {
Log.d(TAG, task.getException().getMessage()); //Don't ignore potential errors!
}
}
});
Because there are several objects within the "Users" node, first you need to get a reference to that node, attach a listener and then loop through the results. The result in the logcat will be:
jm
...
If you want to use the Firebase-UI library, then simply pass the "usersRef" to the FirestoreRecyclerOptions's setQuery() method, as explained in my answer from the following post:
How to display data from Firestore in a RecyclerView with Android?