How can I get the searched value from this FireBase DataSnapshot - android

How can I get the
"Dancing in the dark"
from this snapshot if the snapshot does not exist:? I figure it must be saved in the snapshot somewhere. Please read inline code comments..
private void addListenerForSingleValueEvent(String streetAddress, StringBuilder targetAddress){
DatabaseReference firebase = FirebaseDatabase.getInstance().getReference();
firebase.child("catalog/trax").orderByChild("namn").equalTo("Dancing in the dark")
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
if (snapshot.exists()) {
// do sowm work on existing data
} else {
// How can I get the "Dancing in the dark" from the snapshot?
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(Application.getInstance(), databaseError.getMessage(), Toast.LENGTH_LONG).show();
}
});
}

When you execute a query against the Firebase Database, there will potentially be multiple results. So the snapshot contains a list of those results. Even if there is only a single result, the snapshot will contain a list of one result. By listening to a value event you get all matching results in one snapshot, so you have to iterate over the children.
DatabaseReference firebase = FirebaseDatabase.getInstance().getReference();
firebase.child("catalog/trax").orderByChild("namn").equalTo("Dancing in the dark")
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
for (DataSnapshot item: snapshot.getChildren()) {
// In this loop item is the snapshot of a single item.
// This means we can get the namm of the item
System.out.println(item.child("namm").getValue(String.class));
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(Application.getInstance(), databaseError.getMessage(), Toast.LENGTH_LONG).show();
}
});

Related

How to get child based on value inside it, without knowing the child. in android firebase realtime database

I have a node for the pharmacies accounts and the children are the id of the pharmacies each child contain the name and the id of the pharmacy and some more info. Now I have the pharmacy name and want to get the pharmacy ID is there any function that can do this?
What you're looking for is a database query, which allows you to filter the results under a node based on a property value.
In this case that'd be something like this:
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Pharmacies");
Query query = ref.orderByChild("PharmacyName").equalTo("El Ezaby");
query.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
#Override
public void onComplete(#NonNull Task<DataSnapshot> task) {
if (!task.isSuccessful()) {
Log.e("firebase", "Error getting data", task.getException());
}
else {
DataSnapshot result = task.getResult();
for (DataSnapshot snapshot: result.getChildren()) {
Log.i("firebase", snapshot.child("PharmacyID").getValue(String.class));
}
}
}
});
The loop over result.getChildren() is needed since a query can have multiple results. Even though it may have only one result here, you'll still need the loop.
I have used the above code but there was an error at query.get
The code below worked with me
DatabaseReference databaseReference1=FirebaseDatabase.getInstance().getReference("Pharmacies");
databaseReference1.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for(DataSnapshot dataSnapshot:snapshot.getChildren()){
Pharmacies pharmacies=dataSnapshot.getValue(Pharmacies.class);
if(pharmacies!=null){
if(pharmacyName.contains(pharmacies.getPharmacyName())){
Log.e("firebase", dataSnapshot.child("PharmacyID").getValue(String.class));
pharmacyid=dataSnapshot.child("PharmacyID").getValue(String.class);
}
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});

Retrieve complex nested data from firebase

I have the data in firebase as given below:
I want to get the Customer and Device details for each of the Form ID. The Form IDs are generated uniquely by firebase.
I just somehow need to get access to these Form IDs.
I have set the databaseReference as follows:
databaseReference = FirebaseDatabase.getInstance().getReference("users").child(userID).child("forms");
Then I have tried the following code to retrieve the required data:
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot formsSnapshot : dataSnapshot.getChildren()) {
for (DataSnapshot formIDSnapshot : formsSnapshot.getChildren()) {
Device device = formIDSnapshot.getValue(Device.class);
if (device != null) {
// get and use the data
}
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Update:
I am now successfully able to retrieve the form IDs, thanks to the answer by #Frank.
Now, to get the Device and Customer details I have to write the following code inside the ValueEventListener after getting the form IDs:
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot formsSnapshot : dataSnapshot.getChildren()) {
String formID = formsSnapshot.getKey(); //Retrieving the formID here
//New code addition
// to get the reference to device details node
databaseReference.child(Objects.requireNonNull(formID)).child("Device details").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
Device device = dataSnapshot.getValue(Device.class);
if (device != null) {
// required device details here
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
throw databaseError.toException();
}
});
// to get the reference to customer details node
databaseReference.child(Objects.requireNonNull(formID)).child("Customer details").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
Customer customer = dataSnapshot.getValue(Customer.class);
if (customer != null) {
//required customer details here
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
throw databaseError.toException();
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
throw databaseError.toException();
}
});
I understand that this is a messy code and I would like to get some cleaner approach for the same.
You can get the key of a node by calling DataSnapshot.getKey(). So to get your form IDs:
databaseReference = FirebaseDatabase.getInstance().getReference("users").child(userID).child("forms");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot formsSnapshot : dataSnapshot.getChildren()) {
String formID = formsSnapshot.getKey();
Device device = formsSnapshot.getValue(Device.class);
if (device != null) {
// get and use the data
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
throw databaseError.toException(); // never ignore errors
}
});
There is no need for the nested loops. Simply get the children list and loop over it once. At every iteration, cast dataSnapshot to FormID class and afterwards just use its properties.
i would also suggest that you use SingleValueEventListener instead of ValueEventListener if you do not need to observe the data all the time

Retrieve first child from a parent in Firebase

I am working on an Android application. I want the first child (first UID) of the parent 'support' and store it in a String variable. How do I get the value of the first UID from the list?
I tried one approach. It doesn't work though.
#Override
public void onDataChange(DataSnapshot dataSnapshot1) {
if (dataSnapshot1.exists()) {
String futureUID = "";
for(DataSnapshot futureUIDdatasnapshot:dataSnapshot1.getChildren() ){
futureUID = futureUIDdatasnapshot.getKey();
break;
}
/*Getting the first UID from the list of UID's in queue in 'future'*/
futureUID = dataSnapshot1.getChildren().iterator().next().getKey();
/*Moving a card from 'future' to 'serving'*/
societyServiceUIDReference.child(FIREBASE_CHILD_SERVING).child(futureUID).setValue(FIREBASE_ACCEPTED);
/*Removing the UID from 'future' after it is placed in 'serving'*/
societyServiceUIDReference.child(FIREBASE_CHILD_FUTURE).child(futureUID).removeValue();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
NOTE: 'futureUID' is the UID I want
Try the following:
DatabaseReference ref=FirebaseDatabase.getInstance().getReference().child("support");
Query queryUid=ref.orderByKey().limitToFirst(1);
queryUid.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot datas : dataSnapshot.getChildren()) {
String key=datas.getKey();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Try
DatabaseReference mDatabase;
mDatabase = FirebaseDatabase.getInstance().getReference();
.orderByKey().limitToFirst(n) is what does the trick. It orders the query results by key and returns only the first n results; in this case 1
mDatabase.getChild("support").orderByKey().limitToFirst(1)
.addListenerForSingleValueEvent(new ValueEventListener () {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
for (DataSnapshot supportItem: dataSnapshot.getChildren()) {
String futureUID =supportItem.getKey();
}
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
//Catch your error here
}
});
see Work with Lists of Data on Android

Android Firebase Retrieve Realtime Data

I try to get data from the database.
Code:
mDatabaseUsers = FirebaseDatabase.getInstance().getReference().child("User")mDatabaseUsers.orderByChild("name").startAt("m");
mDatabaseUsers.keepSynced(true); mDatabaseUsers.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Map<String, String> map = dataSnapshot.getValue(Map.class);
String name = map.get("name");
Toast.makeText(AddFriendActivity.this,nick.toString(),Toast.LENGTH_SHORT).show();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
I want to get all users with the letter m!
How does is work?
Thank you!
When you execute a query against the Firebase Database, there will potentially be multiple results. So the snapshot contains a list of those results. Even if there is only a single result, the snapshot will contain a list of one result.
So you'll need to loop over the results in dataSnapshot:
mDatabaseUsers.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot userSnapshot: dataSnapshot.getChildren()) {
System.out.println(userSnapshot.child("name").getValue(String.class));
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException(); // don't ignore errors
}
});
Also see the brief example in the Firebase documentation on using a value event to get a list of results.

How to get nested Child from Firebase Database Using Android?

I want to get list of all Allowed child from this type of JSON Tree:
databaseRef.child('Users').child('Allowded').addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange (DataSnapshot dataSnapshot) {
//
}
}
#Override
public void onCancelled (DatabaseError databaseError) {
} };);
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference userRef = database.getReference("users").child(key).child("Alloweded");
ValueEventListener postListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
User userObj = dataSnapshot.getValue(User.class);
}
#Override
public void onCancelled(DatabaseError databaseError) {
// Getting Post failed, log a message
Log.w(TAG, "loadPost:onCancelled", databaseError.toException());
// ...
}
};userRef.addValueEventListener(postListener);
User is your Model class which have lat, lng, name,no., profileUrl etc
Try this I hope it works fine.
Firebase listeners fire for both the initial data and any changes.
If you're looking to synchronize the data in a collection, use ChildEventListener. If you're looking to synchronize a single object, use ValueEventListener. Note that in both cases you're not "getting" the data. You're synchronizing it, which means that the callback may be invoked multiple times: for the initial data and whenever the data gets updated.
FirebaseRef.child("message").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
System.out.println(snapshot.getValue()); //prints "Do you have data? You'll
love Firebase."
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
databaseRef.child('Users').child('Allowded').addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange (DataSnapshot dataSnapshot) {
for (DataSnapshot childDataSnapshot : dataSnapshot.getChildren()) {
Log.d(TAG, "onDataChange: 1 " + childDataSnapshot.getKey());
for (DataSnapshot childDataSnapshot2 : childDataSnapshot.getChildren()){
Log.d(TAG, "onDataChange: 2 " + childDataSnapshot2.getKey());
}
}
}
}
#Override
public void onCancelled (DatabaseError databaseError) {
} };);

Categories

Resources