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) {
}
});
Related
What I really need is to show every value in the "Income" field in TextView.
250
105
Is this possible? If it is possible please help me.
This is how I insert values to database
private void addReport() {
Float total_Income = Float.valueOf(tv_total_income.getText().toString());
String current_date = tv_current_date.getText().toString();
SimpleDateFormat sdf = new SimpleDateFormat("MMMM");
String currentDateandTime = sdf.format(new Date());
FirebaseDatabase mDatabase = FirebaseDatabase.getInstance();
DatabaseReference mDbRef = mDatabase.getReference("Reports"+"/"+currentDateandTime+"/"+current_date).child("Date");
mDbRef.setValue(current_date);
DatabaseReference mDbRef1 = mDatabase.getReference("Reports"+"/"+currentDateandTime+"/"+current_date).child("Income");
mDbRef1.setValue(total_Income);
}
While Sairaj Sawant's answer might work, keep in mind that there is no need to attach a listener at every iteration of the loop. A more convenient solution is to attach a listener only once, like in the following lines of code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference juneRef = rootRef.child("Reports").child("June");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String totalIncome = "";
for(DataSnapshot ds : dataSnapshot.getChildren()) {
totalIncome = totalIncome + ds.child("Income").getValue(String.class) + " ";
}
Log.d("TAG", totalIncome);
textView.setText(totalIncome);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d("TAG", databaseError.getMessage()); //Don't ignore errors!
}
};
juneRef.addListenerForSingleValueEvent(valueEventListener);
This code will work only if the Income property is of type String, as it is set in your 20-06-2020 child. However, the above code will not work if the value is set as an Integer as it set in your second 21-06-2020 child. Remember, both types of values must match. You either set both as String and the above code will work, or you set them as numbers, case in which you should use this line:
totalIncome = totalIncome + ds.child("Income").getValue(Long.class) + " ";
Try accessing the children of June under Reports and looping through to get income as below :
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference reportsRef = rootRef.child("Reports").child("June");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
String key = ds.getKey();
DatabaseReference keyRef = rootRef.child(key).child("income");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot ds1 : dataSnapshot.getChildren()) {
String income = ds1.getValue(String.class);
Log.d("TAG", income);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
keyRef.addListenerForSingleValueEvent(valueEventListener);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
reportsRef.addListenerForSingleValueEvent(eventListener);
I'm trying to get these values in the node panadol and profinal. but it's not working.
I was able to get the date successfully. Here's my code
for(final String id: MedicinesListActivity.orderIdsList){
//get the date of the order
DatabaseReference dateReference = FirebaseDatabase.getInstance()
.getReference("Orders").child(id);
dateReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
//date
String date = dataSnapshot.child("date").getValue(String.class);
Log.i("Date", date);
//loop through all the products in the specific order id
for(DataSnapshot s : dataSnapshot.child(MedicinesListActivity.userId).child("panadol").getChildren()){
Order order = s.getValue(Order.class);
Log.i("Item_Name", ""+ order.getName());
}
}
});
}
MedicineListActivity.orderIds -> contains all the orderIds i want to loop through
and the class Order contains the name and the orderQuantity.
But it's not working.
To solve this, please use the following lines of code:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidRef = rootRef.child("Orders").child(id).child(uid);
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String name = ds.child("name").getValue(String.class);
String orderQuantity = ds.child("orderQuantity").getValue(String.class);
Log.d("TAG", name + "/" + orderQuantity);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d("TAG", databaseError.getMessage()); //Don't ignore errors!
}
};
uidRef.addListenerForSingleValueEvent(valueEventListener);
The output in the logcat will be:
panadol/3.0
profinal/2.0
Or using the Order class:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidRef = rootRef.child("Orders").child(id).child(uid);
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
Order order = ds.getValue(Order.class);
Log.d("TAG", ds.getName() + "/" + ds.getOrderQuantity);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d("TAG", databaseError.getMessage()); //Don't ignore errors!
}
};
uidRef.addListenerForSingleValueEvent(valueEventListener);
The result will be the same.
In both cases, you have to use all node names in your reference to be able to display that data.
It seems like under each user's node, you have a list of named products (panadol, profinal). Your code looks up one named product panadol in that list with dataSnapshot.child(MedicinesListActivity.userId).child("panadol"):
//loop through all the products in the specific order id
for(DataSnapshot s : dataSnapshot.child(MedicinesListActivity.userId).child("panadol").getChildren()){
Order order = s.getValue(Order.class);
Log.i("Item_Name", ""+ order.getName());
}
Since you then iterate over the child nodes of panadol, your s snapshot refers to the individual properties of panadol: name and orderQuantity. But your code seems to try to map each of those properties to an entire Order object, which won't work.
You have two options:
Show the individual properties, without using the Order class:
for(DataSnapshot propSnapshot: dataSnapshot.child(MedicinesListActivity.userId).child("panadol").getChildren()){
Log.i("Item_Name", propSnapshot.getKey() + "="+ propSnapshot.getValue());
}
Don't use the loop, and get the products and their properties in an Order object:
for(DataSnapshot propSnapshot: dataSnapshot.child(MedicinesListActivity.userId).getChildren()){
Order order = s.getValue(Order.class);
Log.i("Item_Name", propSnapshot.getKey() + "="+ propSnapshot.getValue());
}
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 want to retrieve data for a specific child, how I can write the code? I try a lot, but it did not work:"([ like in my database here how to get the tasks for specific child like lubna and gets all it's child?
Initialize class variables:
private DatabaseReference mDatabase;
mDatabase = FirebaseDatabase.getInstance().getReference();
private DatabaseReference lubnaRef = mDatabase.child("tasks/Lubna");
And then for testing purposes I am assuming you are calling this in your onCreate method of your activity, you'd add the following assuming you do not have a data model for it:
lubnaRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//These are all of your children.
Map<String, Object> lubna = (Map<String, Object>) dataSnapshot.getValue();
for (String childKey: lubna.keySet()) {
//childKey is your "-LQka.. and so on"
//Your current object holds all the variables in your picture.
Map<String, Object> currentLubnaObject = (Map<String, Object>) lubna.get(childKey);
//You can access each variable like so: String variableName = (String) currentLubnaObject.get("INSERT_VARIABLE_HERE"); //data, description, taskid, time, title
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
To solve this, please use the following lines of code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference lubnaRef = rootRef.child("tasks").child("Lubna");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String title = ds.child("title").getValue(String.class);
Log.d(TAG, title);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage());
}
};
lubnaRef.addListenerForSingleValueEvent(valueEventListener);
In the same way you get the title, you can also get the other values. The output in your logcat will be:
Homework
//and so on
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);