I want to delete the Firebase database child, but I can't - java

I want to delete the Firebase database child with this follow code when I click the first item in a list in an app, but I can't. What's wrong?
Query removeCalendar = mCalendarDatabaseReference.limitToFirst(1);
removeCalendar.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String remCal = dataSnapshot.toString();
mCalendarioDatabaseReference.child(remCal).removeValue();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});

Firebase Queries return a list of possible locations where the query might be satisfied, you'd need to iterate through your dataSnapshot to access those locations. Moreover, this :
String remCal = dataSnapshot.toString();
is not going to print the String value of this snapshot. If you want to get the string value of a dataSnapshot it should be:
String remCal = dataSnapshot.getValue(String.class);
If you want to get the reference of a datasnapshot just use getRef(), you don't have to access the original reference.
Query removeCalendar = mCalendarDatabaseReference.limitToFirst(1);
removeCalendar.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot child: dataSnapshot.getChildren()) {
child.getRef().setValue(null); //deleting the value at this location. You can also use removeValue()
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});

I solve the problem with this code:
Query removerCalendario = mCalendarioDatabaseReference.limitToFirst(1);
removerCalendario.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
ds.getRef().removeValue();
}
}

You can do mCalendarioDatabaseReference.child(remCal).setValue(null);

Related

Value of snapshot returns null firebase

I am getting some image ids from firebase but it always returns null even though i am 100% sure data is there and the key names are correct here is my code and firebase database:
String storeidd = getIntent().getStringExtra("storeid");
Query query = FirebaseDatabase.getInstance().getReference().child("Member").child(storeidd).child(childDataSnapshot.getKey()).child("proImages").orderByChild("ImageID").equalTo("1597332319044_0.null");
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
if (snapshot.exists()){
System.out.println(snapshot.child("ImageID").getValue().toString()); // <- returns null
itemArrayList.add(new ClassListItems(childDataSnapshot.child("proname").getValue().toString(),snapshot.child("ImageID").getValue().toString(),childDataSnapshot.child("proprice").getValue().toString(),childDataSnapshot.child("prodesc").getValue().toString()));
myAppAdapter = new MyAppAdapter(itemArrayList, showProducts.this);
listView21.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
listView21.setAdapter(myAppAdapter);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
Also when I print it as System.out.println(snapshot.getValue().toString());
It gives me {-MEcQEJFZCO5Cr0aJSbg={ImageID=1597332319044_0.null}}
Any ideas?
You need to iterate inside the snapshot to be able to get the data:
public void onDataChange(DataSnapshot snapshot) {
if (snapshot.exists()){
for(DataSnapshot ds : snapshot.getChildren()){
String imageID = ds.child("ImageID").getValue(String.class);
}
}
}

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!

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

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

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

How to get random key from firebase in android?

How can I get random key from Firebase realtime database that are stored in list?
Try this:
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("inspirational");
reference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot datas: dataSnapshot.getChildren()){
String keys=datas.getKey();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
First you need to go the dataSnapshot inspirational, then iterate inside of it and, this will give you the random keys String keys=datas.getKey();

Categories