How to get value of parent node as string? - java

So in the above data structure, I want to get value Aprilia Caponord 1200 (marked in fig.). I have Firebase reference to Aprilia (root node) and I can get all the key/value pair data.
Here's my code
#override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot child : dataSnapshot.getChild()) {
Map<?, ?> value = (Map<?, ?>) child.getValue();
String bike_price = value.get("price").toString();
String image_url = value.get("image_url").toString();
}
}
So clearly I can get all the values of child nodes having key/value relations. But I can't specifically get the name of the parent node. So how can I get the value of parent node in String format?
If I print child.getValue().toString(), I get JSON value, but I am not interested in parsing JSON. Is there any specific way to get parent node value?
{Aprilia Caponord 1200={image_url=____________, price=18.35}.. }

You're probably looking for the getKey() method on DataSnapshot:
mFirebaseRef = new Firebase("https://yours.firebaseio.com");
mFirebaseRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot child: dataSnapshot.getChildren()) {
Log.i("MainActivity", child.getKey());
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
Log.e("MainActivity", "onCancelled", firebaseError.toException());
}
});
A few things to note here:
I changed getChild() in your code to getChildren(), since there is not method getChild() that I'm aware of.
You should consider using addChildEventListener, which gives you DataSnapshots on the lower-level nodes
Things will get considerably easier if you create "wrapper classes" for your cars. The Firebase SDK for Android will then automagically unwrap the JSON into instances of that class. See our AndroidChat repo for a good example of this.

I met this case and solved the way as below:
final ChildEventListener countsListener = new ChildEventListener() { //for querying how many card created by each user in a specific period
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
/**
* $ROOT/Apirilia/Apirilia_id/CardId/IMG_URL
* $ROOT/Apirilia/Apirilia_id/CardId/PRICE
* ^[key] :[value]
*/
if (dataSnapshot == null) {
Logger.e("!!! dataSnapshot is null");
return;
}
String apirilia_id = dataSnapshot.getRef().getParent().getKey();
Logger.d("... Apirilia_id:" + apirilia_id);
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
};
I'm appreciated to be able to give one a hand.

for those who looking for key in firebaseUi then this code will work for u:-
firebaseadapterinstance.getRef(position).getKey();

Related

How to retrieve a specific group of children from firebase realtime database

I created a social media app. Suppose I have one array list which contains all the uids of users I follow on my app, stored in child of (following), I also created a child of (posts) which has all posts, posted by all users. The problem is I don't want to use snapshot.getChildern() to retrieve posts which equals following because it downloads whole data under 'posts' child. Is there any way I can retrieve only those posts which matches with 'following' array list?(for Posts Database looks like this)-->
Clicks / UID {title : "sky" imageurl : "https...." publisher : "UID" timestamp : "1666456456.."}
and second one --> follow / UID / following / other user's uid : true
functions I use :
private void checkFollowing(){
followingList = new ArrayList<>();
DatabaseReference reference = Util.getDatabase().getReference("follow")
.child(Objects.requireNonNull(FirebaseAuth.getInstance().getCurrentUser()).getUid())
.child("following");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
followingList.clear();
for (DataSnapshot dataSnapshot : snapshot.getChildren()){
followingList.add(dataSnapshot.getKey());
}
readClicksPosts();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
private void readClicksPosts() {
DatabaseReference reference = Util.getDatabase().getReference("Clicks");
reference.orderByChild("timestamp").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
clicks_models_List.clear();
for (DataSnapshot datasnapshot : snapshot.getChildren()) {
Clicks_Model clicks_model = datasnapshot.getValue(Clicks_Model.class);
for (String id : followingList) {
assert clicks_model != null;
if (clicks_model.getPublisher().equals(id)) {
clicks_models_List.add(clicks_model);
}
}
}
Collections.reverse(clicks_models_List);
clicksAdapter.notifyDataSetChanged();
progressBar.setVisibility(View.GONE);
DatabaseReference.goOffline();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
I just want to show posts from people I follow, what should I do if I don't to use .getChildren() method. Please keep in mind the posts are going to update frequently.

Fetching specified children from firebase realtime database

I am trying to retrieve Messages/child sorted on the base of time. I have access to Messages/child. I am unable to find any useful solution. Please help me figure this out.
My current code is:
FirebaseDatabase.getInstance()
.getReference()
.child("Messages")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable, String s) {
Log.d("children",dataSnapshot.getKey());
users_list.add(dataSnapshot.getKey());
}
you can do this way :-
mChatReference = FirebaseDatabase.getInstance().getReference("Messages")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid());
Query query = mChatReference.orderByChild("time");
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
Log.d("children",dataSnapshot.getKey());
users_list.add(dataSnapshot.getKey());
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
As far as I can see you have a data structure:
Messages: {
uid1: {
uid2: {
messageId1: ...
messageId2: ...
messageId3: ...
}
}
}
You attach a ChildEventListener to /Messages/uid1, which means that your onChildAdded gets called for user second-level UID from your JSON. To get to the individual messages, you still need to loop over the child nodes of the DataSnapshot:
FirebaseDatabase.getInstance()
.getReference()
.child("Messages")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable, String s) {
for (DataSnapshot messageSnapshot: dataSnapshot.getChildren()) {
Log.d("message key: ", messageSnapshot.getKey());
Log.d("message time: ", messageSnapshot.child("time").getValue(String.class));
}
}
A few things to note:
As said, this code loops over the children of the DataSnapshot to get to the individual messages.
Consider storing the data as chat rooms where the key of each chat room is based on the UID of its participants as explained here: Best way to manage Chat channels in Firebase
You will need to add your messages to a list, and sort them client-side.
You're storing the time as a display string, which makes it harder to sort them. Consider storing them in a format that is easier to sort, such as "20190513T073306" or a timestamp such as 1557758003677.

Get Value of Key Based on the Parent Child of Current User Firebase Android

I'm trying to retrieve the value in ServiceFee. I can't do a direct
FirebaseDatabase.getInstance().getReference()
.child("RequestService").child("Plumbers").child(uid)
Because the child below RequestService (like Plumbers) should depend based on the Parent Child of the current user found in Workers
As an example shown in the screenshot, user KO2rC..'s parent child is Plumbers, so I should get that first before I can get the ServiceFee value
I tried the technique in my previous post but I can't seem to recover the value, only the key and I don't need the key
Try this:
FirebaseUser user=FirebaseAuth.getInstance().getCurrentUser();
String uid=user.getUid();
DatabaseReference ref=FirebaseDatabase.getInstance().getReference().child("Workers");
ref.addSingleValueEventListener(new ValueEventListener(){
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot datas: dataSnapshot.getChildren()){
String plumbers=datas.getKey();
DatabaseReference ref=FirebaseDatabase.getInstance().getReference().child("RequestService").child(plumbers).child(uid);
ref.addSingleValueEventListener(new ValueEventListener(){
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String fees=dataSnapshot.child("ServiceFee").getValue().toString();
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
You can do the above, first add the snapshot at child("Workers"),then iterate and retrieve the value which is Plumbers using getKey().
After that add a nested listener and put the retrieved Plumbers inside the child child("RequestService").child(plumbers) and retrieve the value ServiceFee

Ending a Firebase Query/Callbacks in Java

Is there a way to perform a simple query on a Firebase database that gets and returns one object matching the query parameter (in Java)? I'm very new to using Firebase and as far as I can understand the documentation, orderBy() is an asynchronous method that lasts indefinitely, which is why I'm having trouble figuring out how to perform operations on data after the query. Is there some callback notation that allows me to quickly retrieve and return a value and end the query, or am I missing something in the Firebase documentation?
For example, in this method, I want to just figure out if the database contains a specified user and return true if the query matches the user.
public void containsUser(String user) {
DatabaseReference ref = getDatabaseRef("users");
ref.orderByKey().equalTo("user1").addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
System.out.println(dataSnapshot.getKey());
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s){}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {}
#Override
public void onCancelled(DatabaseError databaseError) {
System.out.println(databaseError.getMessage());
}
});
}
Is there an easy way to do this?
To get a single value use addListenerForSingleValueEvent
DatabaseReference ref = getDatabaseRef("users");
ref.child("user1").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String value = (String) dataSnapshot.getValue();
// do your stuff here with value
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});

How Can I get ArrayList of Java Objects of all Childs from Firebase

How Can I get ArrayList of Java Objects of all Childs from Firebase using updated firebase commands, currently I am using below approach but not able to get the list.
ValueEventListener postListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// Get Post object and use the values to update the UI
if(dataSnapshot!=null){
for (DataSnapshot postSnapshot: dataSnapshot.getChildren()) {
UserDataClass post = postSnapshot.getValue(UserDataClass.class);
members.add(post);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
// Getting Post failed, log a message
}
};
mDatabaseRef.addValueEventListener(postListener);
below is datasnapshot which is returning from firebase but I am not able to get the desired result out of it.
DataSnapshot { key = 12345, value = {Members={00000000={phoneNo=00000000, longitude=73.0703307, latitude=33.6396975, password=qwertyuiop, CName=00000000, admin=true, name=Anwar Kamal}, 03028084374={phoneNo=03028084374, longitude=73.0701292, latitude=33.6397129, password=qwerty, CName=00000000, admin=false, name=Nehal Khan}, 03028084516={phoneNo=03028084516, longitude=73.0702659, latitude=33.6397622, password=qwerty, CName=03035356317, admin=false, name=Jamal Khan}}} }
all i want is list of all members
and my java object is
public class UserDataClass {
public double latitude;
public double longitude;
public String Name="";
public String password="";
public String phoneNo="";
public String CircleName="";
public boolean isAdmin=false;
}
The ValueEventListener has another purpose.
You should use ChildEventListener and also dataSnapshop.getValue() to implement what you want, for example:
ChildEventListener childEventListener = new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String previousChildName) {
UserDataClass post = postSnapshot.getValue(UserDataClass.class);
members.add(post);
}
//...
Note:
You should use the listener with the current firebase_referance to the Users table. Hence you should replace
mDatabaseRef.addValueEventListener(postListener);
with
mDatabaseRef.child("Members").addChildEventListener(childEventListener);
notice that your full path of the Members table is colored and i couldn't figure the path.
You can find the whole documentation here
good luck

Categories

Resources