Firebase - Delete specific value without parent key - java

I am attempting to delete a value from a node in Firebase.
It seems that the onDataChange is not being reached.
I tried looking up the docs and articles and used some of the code that I saw referenced in multiple places(e.g. Remove Specific value From Firebase Database). Log statements inside onDataChange are not being called but the Log statements before it are. The scope of email is fine as can be seen by the log statement
I/emailRemove: 111#aol.com
I/removeEmail: Inside Method
In this example I would like to delete whatever area has the email "111#aol.com" :
private void removeEmail() {
Log.i("emailRemove", email);
Log.i("removeEmail","Inside Method");
Query emailQuery = mDatabase.child("emailAddress").equalTo(email);
emailQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot emailSnapshot: dataSnapshot.getChildren()) {
Log.i("snapshot", emailSnapshot.toString());
Log.i("snapshotRef", emailSnapshot.getRef().toString());
emailSnapshot.getRef().removeValue();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.e("TAG", "onCancelled", databaseError.toException());
}
});
}

Since you want to filter by a child property, you should use orderByChild(...):
Query emailQuery = mDatabase.orderByChild("emailAddress").equalTo(email);
emailQuery.addListenerForSingleValueEvent(new ValueEventListener()
You'll also want to make sure you run this query against RC9..., since that is the only node where the child nodes have an emailAddress property.

Related

Read value for random generated child in firebase android

I'm trying to read all the values from my firebase database. My child values are randomly generated using
.push.getkey()
My database structure looks as below:
database structure
Example: child -MFo2XLRF34Pez_xeVAT contains a Jobs object.
How can I get all the values of randomly generated child nodes ? Since i can't pass the values to datasource.child()since I don't know the name of the child.
I just want to save all the Jobs objects into an ArrayList but I can't access them.
Make a Job class with getter and setter for the information you have at that node then to get the data you do this:
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("Jobs");
databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for(DataSnapshot dataSnapshot:snapshot.getChildren())
{
Jobs jobs = dataSnapshot.getValue(Jobs.class);
jobsList.add(jobs);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
the problem was in my databasereference. Instead of assigning databasereference = FirebaseDatabase.getInstance().getReference("Jobs") i was using FirebaseDatabase.getInstance().getReference() which was pointing to the root node. After that dataSnapshot.getValue() worked like a charm.

How to get the random key paired with a specific value in firebase database and delete the value?

I have a simple database structure like so:
I need to remove the value earphone by using its key which is -M-4XBDqv-ve396r5EHm.
I have a button for deleting that value,
and I want to use this line of code to remove it:
mReferenceForListA.child("List A").child("Items").child(key).removeValue().
But how do I get the key for earphone?
I know I can just write
mReferenceForListA.child("List A").child("Items").child(-M-4XBDqv-ve396r5EHm).removeValue()
to delete earphone straight away,
but what if I need to delete other items in the list?
I'll need to pass a specific key into a variable called "key" to delete a specific value.
So, again, how could I get a specific key for the value that I want to delete in my current JSON structure?
This is what I tried:
Reading through related posts for days in stackoverflow and I came down to writing the following codes, but I don't think I got the hang of this thing yet and seriously need help. The following codes always delete the whole "List A" node, but in this case I just need to delete one specified value and keep the others intact in the node.
public static DatabaseReference mRootReference = FirebaseDatabase.getInstance().getReference();
public static DatabaseReference mReferenceForListA = mRootReference.child("List A");
deleteButton= findViewById(R.id.delete_button)
deleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mReferenceForListA.child("Items").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot postsnapshot :dataSnapshot.getChildren()) {
String key = postsnapshot.getKey();
mReferenceForListA.child("Items").child(key).removeValue();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
});
To delete a node you need to know its complete path. If you only know a value of (a property of) the node, you can run a query to find all nodes that match that value.
Something like:
public static DatabaseReference mRootReference = FirebaseDatabase.getInstance().getReference();
public static DatabaseReference mReferenceForListA = mRootReference.child("List A");
Query query = mReferenceForListA.child("Items").orderByValue().equalTo("earphone");
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot: dataSnapshot.getChildren()) {
snapshot.getRef().removeValue();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
throw databaseError.toException();
}
});
The main changes:
The above uses a query on orderByValue() on the Items child. This means Firebase searches all child nodes directly under List A/Items and returns the ones whose value matches earphones.
It also uses addListenerForSingleValueEvent, so that the delete only runs once, instead of continuously.
It uses snapshot.getRef().removeValue() for a much shorter way to remove the node.
It implements onCancelled, since you should never ignore errors.
You should iterate through the DataSnapshot as you have done, but you also need to supply it with a condition to delete the entry with a specific value.
for (DataSnapshot postsnapshot : dataSnapshot.getChildren()) {
if(postsnapshot.child(postsnapshot.getKey()).getValue(String.class)).equals("earphone"){
mReferenceForListA.child("List A").child("Items").child(postsnapshot.getkey()).removeValue();
}
}
Let me know if this works as I am trying to write this from memory.

How to parse all child fields and find what I need in Firebase Database?

I do password recovery and I need to know if there is a user in the database with the entered E-mail'om. How do I do that? Here is the structure:
For example, the user entered E-mail - goshan164#gmail.com and I need to know if there is such a mail in my database. And if it exists, then find out the uID of the user with such mail. How do I do that?
P.S uId initially I do not know. In the picture uId = zKCTYc1JkROrGxgOZgvm9CvfSU42
You're looking for a Firebase database query, in this case one that compares the child property of each node against the value you're looking for:
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("users"); // or whatever your node is
Query query = ref.orderByChild("account").equalTo("goshan164#gmail.com");
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot userSnapshot: dataSnapshot.getChildren()) {
System.out.println(userSnapshot.getKey());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
}
For more on this, see the Firebase documentation on ordering an filtering data.

Firebase: Getting specific field from a node based on field in another node

I have been googling from 3 hours now but have not been able to either phrase the search term correctly or there are no good solutions for it. I am using firebase for my android app. It has a structure like following:
The upper one is comments node
I have just displayed the comments using listview.
commentRef1= FirebaseDatabase.getInstance().getReference().child("Comments").child(postKey1);
commentRef1.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
for(DataSnapshot ds: dataSnapshot.getChildren()){
comment1=ds.getValue(Comment.class);
arrayList.add(comment1);
}
commentList.setAdapter(adapter);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
But as with every relational database, I am trying to save just id or uid in comments(table) or node(rather than whole username).
But, now I am having PROBLEM querying or DISPLAYING USERNAME while displaying comments from the users node (i.e display name) as uid only is saved in comments node.
I found some of the methods like doing nested oneventlistener and so on but little bit confused with the complications and effort need for it.
It would have been simple query or nested select in any sql languages.
Can anybody help? How can i retrieve username or specific value in that query. I saw many storing the while username in comments table. I don't think it is right approach.
To get the full_name, you need to do the following:
DatabaseReference ref=FirebaseDatabase.getInstance().getReference();
commentRef1= FirebaseDatabase.getInstance().getReference().child("Comments").child(postKey1);
commentRef1.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
for(DataSnapshot ds: dataSnapshot.getChildren()){
String userid=ds.child("uid").getValue().toString();
ref.child("Users").orderByKey().equalTo(userid).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String fullname=dataSnapshot.child("full_name").getValue().toString();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
You can use nested listener, I guess you want the user to type the comment then click on a button and creates a node for the comment with a uid,post_id,comment.
Then you want to retrieve the comment to display it with the information, so the datasnapshot will be on Comments/postKey1 then you can retrieve the information there(including the uid), then use orderByKey().equalTo(userid) to be able to retrieve the fullname of the user from the node Users
To avoid all of this just add the fullname in the Comments node instead of the userid
https://firebase.googleblog.com/2013/04/denormalizing-your-data-is-normal.html

Retrieving child value -firebase-

System.out.println(ref.child("mostafa_farahat22#yahoo.com").child("_email"));
*i`m trying to get a value of child but all time i get the URL of the value
how to get the value of this URL as i try by this code but it get me the URLi want to get the _email value.
You are looking at the concept from the wrong angle.
While using the ref.child("mostafa_farahat22#yahoo.com").child("_email") you are just simply pointing at a particular place in your database and nothing more.
If you want to retrieve the data in that particular place, consider these 2 ways.
First if you want to retrieve the data only once, you can do the following :
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
DatabaseReference mostafa = ref.child("Users").child("mostafa_farahat22#yahoo.com").child("_email");
mostafa.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String email = dataSnapshot.getValue(String.class);
//do what you want with the email
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
or maybe you want to retrieve the value in real time and use it in the same time that the database value is changed, all in the same time, whenever the value in changed, then you use this :
mostafa.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String email = dataSnapshot.getValue(String.class);
display.setText(email);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Note the difference between the two methods. First is only for one time retrieve and the second is for retrieving the data whenever the value is changed.
Just have in mind that the codes that i posted are just templates and may need to play with them a bit.
With ref.child("mostafa_farahat22#yahoo.com").child("_email") you are just setting the reference to the object. Take a look at the java firebase documentation to retrieve data.
To get the data you will need to set a listener for your reference
ref.child("mostafa_farahat22#yahoo.com").child("_email").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
// data available in snapshot.value()
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});

Categories