Retrieve Node ID from FireBase Database on CardView Click - java

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().

Related

How to update entry in Firebase Database based on an attribute value

I am using the Firebase Realtime Database with Android in Java. I have the following database screenshot:
I would like to change the availability value (from 0 to 1) for the ingredient with the attribute "ingredient_name = Lime". The attribute ingredient_name is actually something like a primary key meaning that there will be no other database entry with this specific name.
I tried the following code
DatabaseReference rootRef;
rootRef = FirebaseDatabase.getInstance("https://....app").getReference();
String ingredientToBeUpdate = "Lime";
rootRef.child("ingredients").orderByChild("ingredient_name").equalTo(ingredientToBeUpdate).child("availability").setValue(1);
But I get the error "Cannot resolve method 'child' in 'Query'". Can you tell me how to do this update properly? So I would like to update the value from the database entries who attribute "ingredient_name" is equal to a certain string ingredientToBeUpdate.
Firebase doesn't support so-called update queries, where you send a condition and the new data to the database and it them writes the new data for all nodes matching the condition.
Instead you will need to execute the query in your application code, loop through the results, and update each of them in turn:
rootRef
.child("ingredients")
.orderByChild("ingredient_name")
.equalTo(ingredientToBeUpdate)
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot ingredientSnapshot: dataSnapshot.getChildren()) {
ingredientSnapshot.getRef().child("availability").setValue(1);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
}
Also see:
Firebase Android, set value where x = x?
Is it possible to update a specific child's value without ID or key in firebase realtime database from android on button click?

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 add a new "key-value" pair for existing child in firebase

I've connected my android app to firebase and enabled email and password authentication. My current database status is like :
Now I want to add an extra field (key:"number")for all users i have so that my final database looks like:
so please tell me how can I do this ?
One more important thing is I wrote code such that I first authenticate them, if their registration is succesfull then I take user to new Activity where they will enter this "key" after collecting the key I should add this to user node as shown in the second picture.
So please tell me how to do this?
To write a value in the Firebase Realtime Database, you must know the complete path to that value. So in your case that means that you first have to load all data from the database, to be able to determine the dynamic keys (C76w3..., FjsZ..., etc).
Something like this:
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot: dataSnapshot.getChildren()) {
snapshot.getRef().child("key").setValue("hisoka");
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
}

Reading actual Firebase records based on their ids

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

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