Delete multiple datas sharing a same child from Firebase - Java - orderByKey - java

I have the following Firebase Database :
I need to delete all the entries/database objects sharing the same "date_cours" type.
I tried the following method to delete all the entries sharing the same date_cours "10/09/2018", for example :
private void Delete_CR_Lessons(Date date) {
final String date_a_supprimer_string = DateFormat.getDateInstance(DateFormat.SHORT).format(date);
DatabaseReference drTest = FirebaseDatabase.getInstance().getReference("cours");
drTest.child("date_cours").orderByKey().equalTo("10/09/2018")
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.i("Tag", "test1");
for (DataSnapshot postsnapshot :dataSnapshot.getChildren()) {
Log.i("Tag", "test2");
String key = postsnapshot.getKey();
dataSnapshot.getRef().removeValue();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.w("TAG: ", databaseError.getMessage());
}
});
}//fin de la methode Delete_CR_Lessons
I have no error during the execution of the method.
In the Logs, I can see my Log "test1" but not the log "test2".
Does anyone know what I am missing ?

You are providing wrong path and than you are trying to delete wrong datasnapshot value for example try to use: postsnapshot.getRef().removeValue(); instead of dataSnapshot.getRef().removeValue(); because dataSnapshot doesn't point to the value which you want to delete. That is why you used for loop to get all value nodes from your database. Check code below:
DatabaseReference drTest = FirebaseDatabase.getInstance().getReference("cours");
drTest.orderByChild("date_cours").equalTo("01/10/2018")
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.i("Tag", "test1");
for (DataSnapshot postsnapshot :dataSnapshot.getChildren()) {
Log.i("Tag", "test2");
String key = postsnapshot.getKey();
postsnapshot.getRef().removeValue();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.w("TAG: ", databaseError.getMessage());
}
});

Related

Iterate, Check for condition & delete accordingly : Firebase Realtime

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

SingleValueEventListener do not get the value after button click

I need to get nickname value from Firebase Real time database after button is clicked. So i made singleValueListner() in button´s onClick method. But it don´t work.
I have tried debug it, but code didn´t get into singleValueEventListener()
Button getName = (Button)findViewById(R.id.getName);
getName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DatabaseReference db = FirebaseDatabase.getInstance().getReference().child("Member").child(user.getUid());
db.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot data : dataSnapshot.getChildren()) {
TextView tv = (TextView)findViewById(R.id.tv);
tv.setText(data.child("nickname").getValue().toString());
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
});
Database JSON structure:
{
"Member" : {
"1Zuv6VZZ0kPluwc33f1QQQ7DZD93" /* UID */ : {
"-LgIHwiAjfuh5pjK7wzl" : {
"actualScore" : 0,
"bestScore" : 0,
"email" : "some#email.com",
"nickname" : "Vitek",
"season" : 0
}
}
}
}
Database structure:
https://drive.google.com/file/d/15B4b6Rb_WAiS6fioI9gItyijrbDiVjzJ/view
I need to get nickname, I think this is writen good, but not. So, what is wrong?
To get the value of your nickname property, please use the following lines of code:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidRef = rootRef.child("Member").child(uid);
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String nickname = dataSnapshot.child("nickname").getValue(String.class);
Log.d(TAG, nickname);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
}
};
uidRef.addListenerForSingleValueEvent(valueEventListener);
The output in your logcat will be:
Vitek
So there is no need to loop through the DataSnapshot object in order to get the value of your nickname property. If you don't get this result, please check the logcat to see if you have an error message printed out.
You are only referring up to user's id but there is also a parent key of user detail which you need to reference.
tv.setText(data.child("LgiH------").child("nickname").getValue().toString());
but try to remove that second key from your registering user's code because it is not helpful.
You have made a mistake in refering your firebase root node. just change your line as below :
DatabaseReference db = FirebaseDatabase.getInstance().getReference("Member");
Now,just call your singlevalue event.
db.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot data : dataSnapshot.getChildren()) {
TextView tv = (TextView)findViewById(R.id.tv);
tv.setText(data.child("nickname").getValue().toString());
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
This will do your stuff. try debugging your code with log at step by step.

Getting Data from Firebase realtime database, Android Studio, Java

I am looking for a way to get data from the firebase real-time database in a format like an array[] or a String.
My database looks like this:
Link to image of database
Or:
Database
|
-->Users
|
-->UID1
-->UID2
This is at the root of the database
I want to get a list of all of the UIDs in the "Users" child.
This is the code I have so far and am a bit stuck on:
DatabaseReference databaseReference = firebaseDatabase.getReference("Users");
databaseReference.addValueEventListener(
new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String UIDs = dataSnapshot.getValue(String.class);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
I am a bit of a rookie as it comes to java, android studio, and firebase. I am trying to get the data in a format I know how to use like a String or an Array[] of Strings. I looked around if other people had maybe asked the same question, but I could get the answers to those questions to work/didn't understand them.
Thanks in advance for your time!
To get the a list of uids, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference usersRef = rootRef.child("Users");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
List<String> list = new ArrayList<>();
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String uid = ds.getKey();
list.add(uid);
}
//Do what you need to do with your list
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
}
};
usersRef.addListenerForSingleValueEvent(valueEventListener);
I recommend you to use the list only inside the callback otherwise it will be empty. If you want to use it outside the onDataChange() method, I recommend you see the last part of my anwser from this post in which I have explained how it can be done using a custom callback. You can also take a look at this video for a better understanding.
For your above question I will give both ways: ArrayList or String with delimiters
ArrayList<String> uids = new ArrayList<String>();
FirebaseDatabase.getInstance().getReference("Users").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for(DataSnapshot snapshot : dataSnapshot.getChildren()) {
uids.add(snapshot.getKey());
}
}
}
#Override
public void onCancelled(DatabaseError error) {
}
});
For String
String uids = "";
FirebaseDatabase.getInstance().getReference("Users").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for(DataSnapshot snapshot : dataSnapshot.getChildren()) {
uids += snapshot.getKey() + ",";
}
}
}
#Override
public void onCancelled(DatabaseError error) {
}
});
This gives an output such as: uid1,uid2,uid3,.....uidn,
You can try this:
DatabaseReference ref=
FirebaseDatabase.getInstance().getReference("Users");
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
int i = 0;
for(DataSnapshot d : dataSnapshot.getChildren()) {
name[i] = d.getKey();
i++;
}
}
}//onDataChange
#Override
public void onCancelled(DatabaseError error) {
}//onCancelled
});
name[] is an array of strings!

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

Bypass a push id node in firebase

I am getting a null when I try to get data of the child node of a push id. My structure look like this
And this is my code for getting the message data
DatabaseReference mMessageDatabase = FirebaseDatabase.getInstance().getReference().child("private_messages");
mMessageDatabase.child(User1).child(User2).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot != null) {
// getting null in message
String message = dataSnapshot.child("message").getValue(String.class);
Log.e(TAG, "CHAT_LOG: " + message);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Is there something wrong in my code or Am I missing a code there?
EDIT:
I try using a query to test if it gives me data. heres my code
messageDatabase.orderByChild("seen").equalTo("false")
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for (DataSnapshot datas : dataSnapshot.getChildren()) {
String key = datas.getKey();
String seen = dataSnapshot.child(key).child("seen").getValue(String.class);
Log.e(TAG, "CHAT_LOG: Seen= " + seen);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Fortunately it gives me a data. THe only problem is getting the message. I used a query here and I need to give a specific value to it.
Try the following:
mMessageDatabase.child(User1).child(User2).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot != null) {
for(DataSnapshot datas: dataSnapshot.getChildren()){
String message = datas.child("message").getValue(String.class);
Log.e(TAG, "CHAT_LOG: " + message);
}
}
}
Since the snapshot is at User2 then you can loop inside the direct child which is the push id and retrieve the value of child message

Categories