I am trying to retrieve an url from Firebase in Android. However, my problem is that I can't retrieve the url without also getting the unique key of the child.
The value I am trying to retrieve is the following:
Down below is the code I use to retrieve the data from firebase.
final FirebaseDatabase database = FirebaseDatabase.getInstance();
myRef = database.getReference().child("LoadItems");
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot child : dataSnapshot.getChildren() ){
String key;
key = child.getKey();
Log.d(TAG, "onDataChange: " + key);
Log.d(TAG, "onDataChange: " + child.getValue());
}
}
#Override
public void onCancelled(DatabaseError databaseError) { }
});
So what I am trying to get is what the url alone.
There is no need to know any key in order to get that URL. So please use the following lines of code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference shoesRef = rootRef.child("LoadItems").child("Shoes");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String url = ds.getValue(String.class);
Log.d(TAG, url);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
}
};
shoesRef.addListenerForSingleValueEvent(valueEventListener);
Related
I want dataSnapshot to check if "month" exists in its parent's "summary". But dataSnapshot is returning that it does not have "month" in "summary"
ds = FirebaseDatabase.getInstance().getReference("summary");
ds.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//summary
String key = ds.getKey();
if (dataSnapshot.hasChild("month")) {
Toast.makeText(newTransaction.this, "got value", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(newTransaction.this, "No value", Toast.LENGTH_LONG).show();
}
}
My Firebase Database: I want to check the value (blue line) from its parent(red line)
My Firebase Database
The following line of code:
String key = ds.getKey();
Returns the key of the node on which the reference is pointing to, in this case summary. Between the summary node and the month property, there is another level in your structure, which actually is that pushed key (-MJKC ... xGZX). In order to check if that property exists, you need to use that key in the reference too. Assuming that the summary node is a direct node of your Firebase database root, please use the following lines of code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference keyRef = rootRef.child("summary").child("-MJKC_JkVFpCdCGqxGZX");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.hasChild("month")) {
Toast.makeText(newTransaction.this, "got value", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(newTransaction.this, "No value", Toast.LENGTH_LONG).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d("TAG", databaseError.getMessage()); //Don't ignore potential errors!
}
};
keyRef.addListenerForSingleValueEvent(valueEventListener);
However, you haven't store that key into a variable, then you should use a query, as below:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference summaryRef = rootRef.child("summary");
Query queryByMonth = summaryRef.orderByChild("month")
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
Toast.makeText(newTransaction.this, "got value", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(newTransaction.this, "No value", Toast.LENGTH_LONG).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d("TAG", databaseError.getMessage()); //Don't ignore potential errors!
}
};
queryByMonth.addListenerForSingleValueEvent(valueEventListener);
I am trying to write a query to check if there is any "Pending" status on mcustDeliveryStatus. I want to check in Order node that is there any Pending status for mcustDeliveryStatus.
I wrote the following query
mDatabase = FirebaseDatabase.getInstance().getReference("Order");
final Query query = mDatabase.OrderByChild("mcustDeliveryStatus").equalTo("Pending");
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
Toast.makeText(VWelcome.this, "new order", Toast.LENGTH_LONG).show();
Intent i = new Intent(VWelcome.this, ViewOrderRequest.class);
startActivity(i);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
This query works fine but the problem is intent runs even when there is no Pending status in my Order node. Anyone knows why?
Since you annotate your DataSnapshot object with #NonNull, it means that you tell the compiler that your object cannot be null, so it will always return something. With other words, if there are no results, it will return an empty DataSnapshot object. To solve this, you should check how many children are inside that object using the following lines of code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference orderRef = rootRef.child("Order");
Query query = orderRef.orderByChild("mcustDeliveryStatus").equalTo("Pending");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
long count = dataSnapshot.getChildrenCount();
if (count > 0) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String mGasBand = ds.child("mGasBand").getValue(String.class);
Log.d(TAG, mGasBand);
}
} else {
Log.d(TAG, "No data!");
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
}
};
query.addListenerForSingleValueEvent(valueEventListener);
I am trying to create child inside child -LoVaDPuBRr4K2JSkc_j , but how?
Code :
firebaseAuth = FirebaseAuth.getInstance();
firebaseDatabase = FirebaseDatabase.getInstance();
databaseDocument = firebaseDatabase.getReference(firebaseAuth.getUid()).child("Document");
To create a child in -LoVaDPuBRr4K2JSkc_j, you can do:
databaseDocument.child("-LoVaDPuBRr4K2JSkc_j").child("newProperty").setValue("new value");
If you want to generate a new child with an auto-generated key, it'd be:
databaseDocument.child("-LoVaDPuBRr4K2JSkc_j").push().setValue("new value");
Both of these assume that you know the -LoVaDPuBRr4K2JSkc_j value in your code. This is required to be a able to add a child, as writing to a location in the database requires that you know the full path to that location.
You'll not want to hardcode this key of course, so there are two common options to have the key:
Pass it along your app from the moment when you loaded the data.
Use some other value of the node that allows you to perform a query on the database to look up the key.
The simplest solution to add a new property inside your -LoVaDPuBRr4K2JSkc_j object would be use that pushed id in your reference like in the following lines of code:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference ref = rootRef.child(uid).child("Document").child("-LoVaDPuBRr4K2JSkc_j");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
dataSnapshot.getRef().child("newProperty").setValue("newValue");
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
}
};
ref.addListenerForSingleValueEvent(valueEventListener);
Edit:
Accodring to your comment, if you have more than one key, then you should use a query. The following code will do the trick:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
Query query = rootRef.child(uid).child("Document").orderByChild("inspectorName").equalTo("Test");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
ds.getRef().child("newProperty").setValue("newValue");
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
}
};
query.addListenerForSingleValueEvent(valueEventListener);
My code and its work :
firebaseAuth = FirebaseAuth.getInstance();
firebaseDatabase = FirebaseDatabase.getInstance();
databaseProduct = firebaseDatabase.getReference(firebaseAuth.getUid()).child("Document");
String id = databaseProduct.push().getKey();
final String productID = databaseProduct.child(id).child("Product").push().getKey();
final Items items = new Items(productID, dates, nameInspector, locate, product, priceProduct, amount, code);
databaseProduct.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot getDocumentKey : dataSnapshot.getChildren()) {
String getDocumentID = getDocumentKey.getKey();
String sameDocumentID = getDocumentKey.child("documentID").getValue().toString();
if (getDocumentID.contentEquals(sameDocumentID)) {
databaseProduct.child(getDocumentID).child("Product").child(productID).setValue(items);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
I have the following database. What I need is to get the total count of comments per post when posting UID equal to current_user_uid.
Any suggestion on how to do this?
To solve this, please use the following code:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
Query query = rootRef.child("Posts").orderByChild("uid").equalTo(current_user_uid);
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
long count = ds.child("comments").getChildrenCount();
Log.d("TAG", "Count: " + count);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage());
}
};
query.addListenerForSingleValueEvent(valueEventListener);
So I have some data in my Firebase. It's structure is
(assume that there is more data)
I want to get the records where banknoteType ="100_dollar" and userId="1057..."
DatabaseReference database = FirebaseDatabase.getInstance().getReference("userBanknoteAmount");
Query firebaseQuery = database.orderByChild(1057...).equalTo(1057...);
firebaseQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
//todo
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.w("onCancelledError", "loadPost:onCancelled", databaseError.toException());
}
});
But the onDataChangeevent doesn't fire... What am I mistaking?
EDIT: I am trying to debug it and neither onDataChange nor onCancelled breakpoints stop there
EDIT 2 : The current code I am using is
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference userBanknoteAmountRef = rootRef.child("userBanknoteAmount");
Query firebaseQuery = userBanknoteAmountRef.orderByChild("userId");//.equalTo(userId);
firebaseQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
Log.d("test", "onDataChange: "+postSnapshot);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.wtf("onCancelledError", "loadPost:onCancelled", databaseError.toException());
}
});
EDIT 3: https://i.stack.imgur.com/iBkcx.png
Firebase Realtime database does not allow you to chain multiple filter methods. If you want to get the records where : userId="1057...", please change the following line of code:
Query firebaseQuery = database.orderByChild(1057...).equalTo(1057...);
with
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference userBanknoteAmountRef = rootRef.child("userBanknoteAmount");
Query firebaseQuery = userBanknoteAmountRef.orderByChild("userId").equalTo(1057...);
If you want to get all the records where banknoteType ="100_dollar" and userId="1057...", please see my answer from this post.
According to your edited post, please also change this line of code:
Log.d("test", "onDataChange: "+postSnapshot);
to
Log.d("test", "onDataChange: "+postSnapshot.child("userId").getValue(String.class));