In one of my activities I insert some data to the Firebase database. In another activity I want to check if the child of the inserted data exists. If the key exists I want to get the root unique key.
Problem:
I have this database structure:
I want to check if the username child exists. If it exists I want to get the root key. Both the root unique key and the username node is marked with red.
What I have done
//variable username is the actual username of the current user
userRef.child(sharedPreferences.getString("school", null)).child("routes").orderByChild("username").equalTo(username).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
String key=ds.getKey();
System.out.println("key" + key);
}
}
But I don't now how to get inside the drivers node, and how to get the root unique key. Any ideas?
Yes you can, using exists() method.
userRef.child("routes").child(routeId).child("drivers").child(userName).addListenerForSingleValueEvent(new
ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
//do something
}
}
If you want to verify the existents of username accross all routes, assuming that routes node is a direct child of your Firebase database, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference routesRef = rootRef.child("routes");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
if(ds.child("drivers").child(userName).exists()) {
//do what you want
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
routesRef.addListenerForSingleValueEvent(eventListener);
In which userName is the name of the user that you want to be checked for existent.
You're almost there. You can pass in a path to orderByChild() to filter on the property at that path. So:
userRef.child(sharedPreferences.getString("school", null))
.child("routes").orderByChild("drivers/username").equalTo(username).addListenerForSingleValueEvent(new ValueEventListener() {
Now your onDataChange will get called with a snapshot of all nodes that have the required user name. So looping over them and printing is the same as you had:
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
String key=ds.getKey();
System.out.println("key" + key);
}
}
if(ds.hasChild("drivers")){
String key=ds.getKey();
}
you can do this:
userRef.child("routes").orderByChild("username").equalTo("jju").addListenerForSingleValueEvent(...){ //code here }
edit:
userRef.child("routes").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
if(ds.hasChild("driver"){
for(DataSnapshot data : ds.getChildren()){
if(data.child("username").exists()){
String key=ds.getKey();
System.out.println("key" + key);
}
}
}
}
}
Related
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.
I have to fetch all children data from firebase real time database? I want to fetch received messages of User2. How to do that? Database example is as given below -
To be able to fetch the children data, try the following:
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("users").child("User1").child("MSG_TYPE_SENT");
reference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot datas: dataSnapshot.getChildren()){
String msgContent=datas.child("msgContent").getValue().toString();
String msgType=datas.child("msgType").getValue().toString();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
This will give you the msgContent and the msgType, to retrieve any data from the database, you need to pass through every node example:-
getReference("users").child("User1").child("MSG_TYPE_SENT");
Then you can loop inside the ids and retrieve the data.
Here you can fetch the User2 Messages Received
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference("users");
mDatabase.child("User2").child("MSG_TYPE_RECEIVED").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot spanshot : dataSnapshot.getChildren()){
String content=snapshot.child("msgContent").getValue(String.class);
String type=snapshot.child("msgType").getValue(String.class);
//then you can log those values
Log.d("Values:",""+content+""+type);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
If the message received change at any time (lets say you want to implement the delete option in realtime of the message like whatsapp) .addValueEventListener will update your UI in realtime if you have coded to show that the message has been deleted
-patient
-9876543210
-hjsfrhwugfshgjgjwwg
-name
-description
-tokennumber
-disease
-date-'24/12/91'
-hjsfrhwugfshgjgjwwg
-name
-description
-tokennumber
-disease
-date-'24/12/91'
-9876543211
I'm having data like this. I want to show the all child which meets conditon that date=24/12/91.`before im using push I can retrieve all child data from patient.but after using unique keys I cant retrieve.this is my previous code.
I'm having data like this. I want to show the all child which meets conditon that date=24/12/91.`before im using push I can retrieve all child data from patient.but after using unique keys I cant retrieve.this is my previous code.
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
Query query = reference.child("patient").orderByChild("dates").equalTo(date);
query.addListenerForSingleValueEvent(new ValueEventListener() {
public ArrayList<HashMap> hashMap;
public HashMap<String, String> hash;
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
medical_list = new ArrayList<>();
for (DataSnapshot patient : dataSnapshot.getChildren()) {
String name = patient.child("name").getValue(String.class);
String description = patient.child("description").getValue(String.class);
String tokennumber = patient.child("tokennumber").getValue(String.class);
String disease = patient.child("disease").getValue(String.class);
medicaldetail medi = new medicaldetail(name, description, tokennumber, disease);
medical_list.add(medi);
}
act_adapter obj = new act_adapter(Reports.this, medical_list);
listview.setAdapter(obj);
obj.notifyDataSetChanged();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
`
[1]: https://i.stack.imgur.com/spcZt.png
Your problem in your code is that you are missing a child in your query and for that, please change the following line of code:
Query query = reference.child("patient").orderByChild("dates").equalTo(date);
to:
Query query = reference.child("patient").child(patientId).orderByChild("dates").equalTo(date);
In which patientId is the id of the patient that you are looking for to meet condition. For example could be: 9876543210.
Edit:
According to your comment, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference patientRef = rootRef.child("patient");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String mobileNumber = ds.getKey();
DatabaseReference mobileNumberRef = patientRef.child("mobileNumber");
Query query = mobileNumberRef.orderByChild("dates").equalTo(date);
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) {}
};
query.addListenerForSingleValueEvent(eventListener);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
patientRef.addListenerForSingleValueEvent(valueEventListener);
change your query like this ..
Query query = reference.child("patient").child("9876543210").child(databasereferenceobject.getKey()).orderByChild("date").equalTo(date);
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
I have looked at a few other answers for similar problems but don't understand why mine isn't working.
In my firebase database, I have a list of users that have different information under them. I would like to retrieve information from a current userId to recyclerview.
My code looks like:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference databaseStatus = rootRef.child("other");
String uid = firebaseAuth.getInstance().getCurrentUser().getUid();
databaseStatus.child(uid).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
for (DataSnapshot ds : snapshot.getChildren()) {
for (DataSnapshot dSnapshot : ds.getChildren()) {
OtherClass otherClass = dSnapshot.getValue(OtherClass.class);
Log.d("Show", otherClass.getOname() == null ? "" : otherClass.getOname());
list.add(otherClass);
}
adapter = new ShowOtherDetails.OtherAdapter(ShowOtherDetails.this, list);
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
progressDialog.dismiss();
}
}
which gives me this error :
com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.String to type com.mycare.OtherClass
firebase data structure looks like this:
Please, can someone help me out?
Try this:
When saving do this:
String key = databaseStatus.child(uid).push().getKey()
so you will be able to get the key.
then add the key as a child when retrieving here in the first method
databaseStatus.child(uid).child(key).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
OtherClass otherClass = snapshot.getValue(OtherClass.class);
Log.d("Show", otherClass.getOname() == null ? "" : otherClass.getOname());
list.add(otherClass);
}
Remove the for loop for (DataSnapshot ds : snapshot.getChildren())
Or do this:
databaseStatus.child(uid).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
for (DataSnapshot ds : snapshot.getChildren()) {
for (DataSnapshot dSnapshot : ds.getChildren()) {
String date=dataSnapshot.child("date").getValue().toString();
String detail=dataSnapshot.child("detail").getValue().toString();
String email=dataSnapshot.child("email").getValue().toString();
String id=dataSnapshot.child("id").getValue().toString()
//and so on
}
i hope its work, Try this
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
String date= ds.child("date").getValue(String.class);
String detail= ds.child("detail").getValue(String.class);
String email= ds.child("email").getValue(String.class);
String id= ds.child("id").getValue(String.class);
Log.d("TAG", date+ " / "+detail+" / "+email+" / "+id);
OtherClass otherClass = new OtherClass(date,detail,email,id);
listdata.add(otherClass);
}
recyclerView.setAdapter(adpter);
adpter.notifyDataSetChanged();
}