Reading actual Firebase records based on their ids - java

Let's say I have a Firebase Realtime database structure where there are user nodes and each user node has post nodes that only contain post ids. Then there are also separate post nodes where the actual posts reside (flat data structuring). The structure is described in detail in this answer.
Now if I can get the ids of the posts of each user by attaching a listener to that user's posts node, how can I retrieve the posts themselves (full information from a post node)? I know there aren't any queries where one can pass a bunch of keys and get the associated records. Should I just attach a listener to each post node I am interested in? I'm currently afraid there might be some serious performance issues, because the number of posts is practically unlimited.

Using the exact database structure from this post, to solve your problem, you need to query your database twice. Once to get the post ids of the particular user you need and second to get the posts it self. To achieve this, please use the following code:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference postsRef = rootRef.child("users").child(uid).child("posts");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String postId = ds.getKey();
DatabaseReference postIdRef = rootRef.child("posts").child(postId);
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot dSnapshot : dataSnapshot.getChildren()) {
String postName = dSnapshot.child("postName").getValue(String.class);
Log.d("TAG", postName);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
postIdRef.addListenerForSingleValueEvent(eventListener);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
postsRef.addListenerForSingleValueEvent(valueEventListener);

Related

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.

Retrieve Node ID from FireBase Database on CardView Click

I have a firebase database I am using with Android.
To Retrieve and show data from Firebase, I am using FirebaseRecyclerAdapter and results are displayed to CardView.
Now I am getting all listings from my required table to CardView. Every Node has an automatically generated value as shown in the image below.
How do I retrieve this value in Android when I click on respective CardView. I'll need this value for further database operations.
Now, I tried some of the methods posted here as well as online forums but nothing seems to work. I am not asking for complete code, just how to do it? Some reference code would be great.
Regards
To get the node id try the following:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
Query query = rootRef.child("Projects");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String key = ds.getKey();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage());
}
};
query.addListenerForSingleValueEvent(valueEventListener);
First, add a reference to node Projects then loop inside of it and retrieve the id using getKey().

Fetch a data in Firebase using another data

This is the Firebase database structure of my project.
I want to fetch complaint division, describe, stat for the particular hostelname and roomno. How to fetch these data and display in android project?
To get all those values, please use the following lines of code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference complaintsRef = rootRef.child("Complaints");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String complaintDivision = ds.child("complaintdivision").getValue(String.class);
//Get the other properties in the same way
Log.d(TAG, complaintDivision);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
}
};
complaintsRef.addListenerForSingleValueEvent(valueEventListener);
The output in your logcat will be:
Plumber Related
This is a basic function in Firebase on Android. You can use ValueEventListeners with the database reference to do this.
The steps to achieve the desired results can be enlisted as below:
Create a Complaint model with the same fields as your database.
Get the right Firebase reference for your database node and add a ValueEventListener instance to listen for database changes.
Pass a DataSnapshot into the Complaint class and assign it to a Complaint object.
Do what you want with the Complaint object you have obtained.
Creating a Complaint class:
class Complaint {
// your fields should have the same name as database fields to prevent unnecessary complications
public String complaintdivision;
public String complaintid;
public String describe;
public String hostelname;
public String roomno;
public String stat;
public Complaint(){// required for Firebase
}
}
Getting the data from Firebase:
ArrayList<Complaint> myComplaintArrayList = new ArrayList<>();
FirebaseDatabase.getInstance().getReference().child("Complaints").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot complaint: dataSnapshot.getChildren()){
Complaint c = complaint.getValue(Complaint.class);
myComplaintArrayList.add(c);// you should have an ArrayList<Complaint> for this loop
}
// do what you want with the items you obtained
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
throw databaseError.toException();
}
});
This is pretty much all of it. If you are still having problems, you should read a tutorial on Firebase.
So to fetch the data you would first declare a Firebase DatabaseReference object that points to your database:
private DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference();
You would then write a query using this object:
Query query = mDatabase.child("Complaints");
Now you attach a SingleValueEventListener to this query:
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//Write a for-each loop to cycle through your node's children
for(DataSnapshot data: dataSnapshot.getChildren()){
//Create an instance of your model class to
//store the received data
//Make sure you have an empty constructor in your model class
Complaint complaint = data.getValue(Complaint.class);
//then simply call your getters on the complaint object
//to get what you need
complaint.getComplaintDivision();
complaint.getDescription();
//...
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
To fetch more specifically, you just modify the query.
For more information on queries, see this

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