Iterate, Check for condition & delete accordingly : Firebase Realtime - java

I'm using Firebase realtime database. Below is the structure
Problem Statement: Over a list of "Users", I need to delete child who's having coins = 0
So far I'm stuck here
DatabaseReference deleteRef = dbref.child("Users").child("coins");
Query deleteQuery = deleteRef.orderByValue().equalTo("0");
deleteQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for (DataSnapshot child : dataSnapshot.getChildren()) {
child.getRef().setValue(null);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
});
Any help will be appreciated :)

You need to order the list by the child coins like here:
DatabaseReference deleteRef = dbref.child("Users");
Query deleteQuery = deleteRef.orderByChild("coins").equalTo("0");
deleteQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for (DataSnapshot child : dataSnapshot.getChildren()) {
child.getRef().setValue(null);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
});

Related

Firebase Database Not in Sync

I want to keep the addToCart button in sync with the Firebase database. The button should be enabled if the checkForActiveOrdersQuery has no children, otherwise, it should be disabled.
The issue with the below code is that the keepSynced(true) is not working.
checkForActiveOrders = FirebaseDatabase.getInstance().getReference("activeOrders");
checkForActiveOrdersQuery = checkForActiveOrders.child(restaurantID).child(tableID);
checkForActiveOrdersQuery.keepSynced(true);
checkForActiveOrdersQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
String orderIDKey = dataSnapshot1.getKey();
if (!dataSnapshot.hasChildren()) {
addToCartButton.setEnabled(true);
} else if (!orderIDKey.equals(orderID)){
addToCartButton.setEnabled(false);
} else if (orderIDKey.equals(orderID)) {
addToCartButton.setEnabled(true);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});

How to retrieve all Uid without currentUser?

I don't know how to retrieve all Uid. This is my data:
this is my snippet code to set the data:
reference = db.getReference("Attendance");
reference.child(id).child(uid).child.("Status").setValue(status);
any help thank you guys
To log all UIDs (and names) from the JSON:
reference = db.getReference("Attendance");
reference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot idSnapshot: dataSnapshot.getChildren()) {
System.out.println(idSnapshot.getKey());
for (DataSnapshot userSnapshot: idSnapshot.getChildren()) {
System.out.println(userSnapshot.getKey());
System.out.println(userSnapshot.child("Status/xname").getValue(String.class));
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
}

Firebase RealTime Database Delete First 20 item

DatabaseReference newReferance = database.getReference().child("Users");
Query query = newReferance.orderByChild("timestamp");
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
chatMessages.clear();
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
HashMap<String, String> hashMap = (HashMap<String, String>) dataSnapshot1.getValue();
//String userMail = hashMap.get("useremail");
String userMessage = hashMap.get("usermessage");
String userCt = hashMap.get("usershow");
chatMessages.add(userCt + ": " + userMessage);
if (chatMessages.size() >= 10){
for (int i= 0; i < 5; i++){
//HOW ????
}
}
recyclerAdapter.notifyDataSetChanged();
}
}
Hi Dear guys. How do I select and delete the first 5 data in a real-time database? When the ArrayList reaches a certain limit, I want to delete the first 5 data from the database. I'd appreciate it if you could help with the problem.
How do I select and delete the first 5 data in a real-time database?
You can achieve this using Firebase Query's limitToFirst(int limit):
Create a query with limit and anchor it to the start of the window
And in code should look like this:
Query query = newReferance.orderByChild("timestamp").limitToFirst(5);
See I have used this limitToFirst() method that can help you find the first 5 items. To delete them, just attach a listener and inside the onDataChange() method use the following line of code:
dataSnapshot.getRef().removeValue();
final DatabaseReference newReferance = database.getReference().child("Users");
final Query query = newReferance.orderByChild("timestamp");
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
chatMessages.clear();
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
HashMap<String, String> hashMap = (HashMap<String, String>) dataSnapshot1.getValue();
//String userMail = hashMap.get("useremail");
String userMessage = hashMap.get("usermessage");
String userCt = hashMap.get("usershow");
chatMessages.add(userCt + ": " + userMessage);
if (chatMessages.size() >= 10){
Query query1 = newReferance.limitToFirst(5);
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
database.getReference().child("Users").setValue(null);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
recyclerAdapter.notifyDataSetChanged();
}
}
Although I'm set, it's all deleted. I can't erase the items I want. All cleared.
rootRef is the firebase database reference. whose instance we have to gained before trying to delete any value. you can see the code given below.
count = 0;
rootRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
for (DataSnapshot postSnapshot : snapshot.getChildren()) {
CommonLocationClass user = postSnapshot.getValue(CommonLocationClass.class);
if (count < 5) {
rootRef.child(user.getPhNo).removeValue();
count++;
}
}
}
}
#Override
public void onCancelled (DatabaseError firebaseError){
}
});
the CommonLocationClass is a getter setter model class i have made to make the fire-base implementation easy
you can try this it works for me
public void getDataFirebase() {
/*if (chatMessages.size() == MAX_MSJ_LIMIT){
database.getReference().child("Users").removeValue();
}*/
final DatabaseReference newRefere = database.getReference().child("Users");
Query query = newRefere.orderByChild("timestamp");
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
chatMessages.clear();
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
HashMap<String, String> hashMap = (HashMap<String, String>) dataSnapshot1.getValue();
//String userMail = hashMap.get("useremail");
String userMessage = hashMap.get("usermessage");
String userCt = hashMap.get("usershow");
chatMessages.add(userCt + ": " + userMessage);
recyclerAdapter.notifyDataSetChanged();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(getApplicationContext(), databaseError.getMessage(), Toast.LENGTH_LONG).show();
}
});
if (chatMessages.size() >= 10) {
Query query1 = newRefere.orderByChild("timestamp").limitToFirst(5);
query1.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
dataSnapshot.getRef().removeValue();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
It didn't just erase the first 5 data.
if (chatMessages.size() >= 10) {
Query query1 = newRefere.orderByChild("timestamp").limitToFirst(5);
query1.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()){
ds.getRef().removeValue();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
I solved the problem. With this code

Firebase realtime database - how to get parent name based on a value of one of its keys

The structure looks like this:
users
|----username1
|----uid:value
username2
|----uid:value
I'm trying to find the best way to get the username value based of the value of it's uid,
This need to be in Java code (Android), So far I found the following code:
Query uid = reference.child("users").orderByChild("uid").equalTo(uid);
uid.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot datas: dataSnapshot.getChildren()){
String keys=datas.getKey();
if (keys.equals(uid)) {
// uid found
} else {
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Try this code and create a model class to fetch value of Uid
DatabaseReference users= FirebaseDatabase.getInstance().getReference().child("users");
users.orderByChild("uid").equalTo(uid).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot post:dataSnapshot.getChildren()){
//Use a model class to fetch user id like below
UIDDetails u=post.getValue(UIDDetails.class);
String user_id=u.getUid();
//Here all values will be equal to youy required uid if exists more than one
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Please add below code into your file:
DatabaseReference users= FirebaseDatabase.getInstance().getReference().child("users");
final Query userQuery = users.orderByChild("uid");
userQuery.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
map.clear();
if(child.getkey().toString().equalsIgnoreCase(uid)){
//Get the node from the datasnapshot
String myParentNode = dataSnapshot.getKey();
for (DataSnapshot child: dataSnapshot.getChildren())
{
String key = child.getKey().toString();
String value = child.getValue().toString();
map.put(key,value);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
databaseError.toException();
}
});

What is the best way to check the existence of every child in one node?

FirebaseDatabase.getInstance().getReference("Block").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snap : dataSnapshot.getChildren()) {
if(snap.getKey().equals(myUID)){
FirebaseDatabase.getInstance().getReference("Block").child(myUID).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snap : dataSnapshot.getChildren()) {
if(snap.getKey().equals(list.get(position).getUid())){
FirebaseDatabase.getInstance().getReference("Block").child(myUID).child(list.get(position).getUid()).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snap : dataSnapshot.getChildren()) {
if(snap.getValue().equals("1")){
call_method();
}else{
//code...
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
} else {
call_method();
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
} else {
call_method();
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
This code works well, but it is very long so I am asking for the best way to write it ?
I want to check firstly if Block node has child equals to my UID if it is true then I want to check if my UID has child equals to specific UID if it is true then I want to get the value of block which is 0 in this example
How can I do that ? Thank you very much.
Just traverse to the path specified using child. You will get no data if the path doesn't exist.
FirebaseDatabase.getInstance().getReference("Block")
.child("MyUUID")
.child("specificUUID")
.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()) {
// ... Do something
} else {
call_method();
}
// ... Other code
}
Try this:
Firebaseuser user=FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Block");
ref.child(user.getUid()).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exist()){
//checks first uid
if(dataSnapshot.hasChild(seconduid){
//checks if seconduid is there
for(DataSnapshot datas:dataSnapshot.getChildren()){
String blocks=datas.child("block").getValue().toString();
}
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
This will check the first uid if(dataSnapshot.exist()) after that it will check if that uid node has the second uid that you provide if(dataSnapshot.hasChild(seconduid){ then you will iterate and get the node block

Categories