dataSnapShot.getChildren() returning null - java

I'm trying to fetch the user details of a particular user using a query:
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
Query query = reference
.child("user_account_settings"))
.orderByChild("user_id")
.equalTo(getItem(position).getUser_id());
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.d(TAG, "onDataChange: the fetched user id is " + getItem(position).getUser_id());
for(DataSnapshot singleSnapshot : dataSnapshot.getChildren()){
//do stuff
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Firebase database screenshot
The user id that is fetched is correct according to the database and it clearly has children, but for some reason dataSnapshot.getChildren() is empty thus not allowing me to iterate through the foreach loop.

The problem in your code lies in the fact that the user ID property is called in the database userid, while in your query you are using user_id, which is incorrect. The name of the field in your query must match the name field in the database. To solve this, simply change:
.orderByChild("user_id")
To:
.orderByChild("userid")

Related

Firebase Realtime Database geting User by Email/Name in Android with Java

I want to get a User or just a User UID via email or name. Tried to write the query, but I'm getting all users and then iterating through them and then getting the user but I think it's an expensive task. How can I get only one User/Uid from Realtime Database?
This is what I came up with (But don't think is the best way):
DatabaseReference usersRef = FirebaseDatabase.getInstance().getReference("Users");
Query emailQuery = usersRef.orderByChild("email").equalTo(client.getEmail());
emailQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot child : snapshot.getChildren()) {
if (child.getValue(User.class).getEmail().equals(client.getEmail())){
User user = child.getValue(User.class);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
According to your last comment:
I have the corresponding details of each user (email, name), and I want to get the UID of one user (no matter which one)
To get a particular user from the database based on a particular email address, the query that you are already using:
Query emailQuery = usersRef.orderByChild("email").equalTo(client.getEmail());
Returns only the users who have the field email set to what client.getEmail() returns. For instance, if client.getEmail() returns tedo#gmail.com then you'll get a single result, according to your screenshot, which is the first one. That being said, the following if statement, doesn't make sense to be used:
if (child.getValue(User.class).getEmail().equals(client.getEmail())){
User user = child.getValue(User.class);
}
Since the key of the user node is represented by the UID, then you should get it like this:
Query emailQuery = usersRef.orderByChild("email").equalTo(client.getEmail());
emailQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot child : snapshot.getChildren()) {
User user = child.getValue(User.class);
String uid = child.getKey();
//Do what you need to do with UID.
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Log.d("TAG", error.getMessage()); //Never ignore potential errors!
}
});
That's the simplest, cheapest way to query the Realtime Database, in which you return only the elements that you are interested in and that satisfy a particular condition.

Firebase: child of child extract value

how can I extract all the "name" values contained in DATA?
I tried this to extract a single name but it doesn't work:
DatabaseReference myRef = FirebaseDatabase.getInstance().getReference("ALL");
Query query = myRef.orderByChild("name").equalTo("pluto");
Two problems:
The code you shared only declares a query. It doesn't read anything from Firebase yet.
You're trying to order/filter in a child property, but are not specifying the full path to that property.
The second one is easiest to fix:
DatabaseReference myRef = FirebaseDatabase.getInstance().getReference("ALL");
Query query = myRef.orderByChild("DATA/name").equalTo("pluto");
And then you can read the results with:
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot: dataSnapshot.getChildren()) {
Log.i("Firebase", snapshot.getKey());
Log.i("Firebase", snapshot.child("name").getValue(String.class));
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
}
Thanks
I edited it so the log is working
Log.i("Firebase", snapshot.child("DATA/name").getValue(String.class));
If I want to print all the names, how should I do it?

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.

How to get a child's data when it has been pushed?

I am using the "push()" function to store objects into my firebase database and since it stores data with unique keys I can't change the stored objects values using what's mentionned in the documentation:
myRef.child("child name").setValue(model);
because I simply don't know the key. I wan wondering is there an other way to modify the data of firebase database.
I want to add a new child called "conversations" to the users and programmatically add childs to him .
and this is the databse structure:
If you have the following database:
Users
pushId
name : john
age : 100
In case you dont know the pushId, you can do the following:
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("Users");
databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()){
String key = ds.getKey();
String name = ds.child("name").getValue().toString();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
The above will get you the name and the key using getKey()

FirebaseDatabase Query : How to query some data basing on some values from other childs. For FirebaseRecyclerAdapter

I'm working on my app that has a fragment, this fragment displays new users with a follow button using this query :
query = mDatabaseref.child("users").orderByChild("date").limitToLast(10);
After a follow button is clicked, the current User Uid gets saved as a child in the other child that has a name "Follows" with 2 other child's "following" and "followers" as it showed in the below picture :
what I want to do is to make a Query for an other fragment with the name Following and show all the users that the Current user is following with the ability of getting their names, I was thinking of making a data dataSnapshot in the FirebaseRecyclerAdapter onBindViewHolder method basing on the Uid tooken from the childs, but I think it's gonna be complex, on the other hand, i tried to sort the follows in the user Info child direclty, but it leads to a strange behaviour on the RecyclerView.
I'm not going to write you all the code including your FirebaseRecyclerAdapter, I will show you just how to query to get the desired results. As i understand, here is the problem. So in order to achieve this, you need to query your database twice, once to get all those ids and second, based on those ids to get the names. So, please use the following code:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference followingRef = rootRef.child("follows").child(uid).child("following");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String userId = ds.getKey();
DatabaseReference userIdRef = rootRef.child("users").child(userId);
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot dSnapshot : dataSnapshot.getChildren()) {
String name = dSnapshot.child("name").getValue(String.class);
Log.d("TAG", name);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
userIdRef.addListenerForSingleValueEvent(eventListener);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
followingRef.addListenerForSingleValueEvent(valueEventListener);
The result in your logcat will be all the names of the followers that belong to a single user.

Categories