i need to sum all items and price from my firebase database but every time i add item the sum multiply so what can i do to have the correct sum of items
cou.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postS: dataSnapshot.getChildren() ){
ProductVar productVar = postS.getValue(ProductVar.class);
JumlaKuu += Integer.parseInt(productVar.getTotal());
ItemsKuu += Integer.parseInt(productVar.getItem());
Log.d("onVil2: ", String.valueOf(JumlaKuu));
}
jumla.setText(String.valueOf(JumlaKuu));
itemsNumberView.setText(String.valueOf(ItemsKuu));
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
In your code old sum is also added into new one because you didn't set sum to 0 when your addValueEventListener gets fired. So, for getting correct sum every time you just have to set JumlaKuu & ItemsKuu values to 0 as below code.
cou.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
JumlaKuu = 0;
ItemsKuu = 0;
for (DataSnapshot postS: dataSnapshot.getChildren() ){
ProductVar productVar = postS.getValue(ProductVar.class);
JumlaKuu += Integer.parseInt(productVar.getTotal());
ItemsKuu += Integer.parseInt(productVar.getItem());
Log.d("onVil2: ", String.valueOf(JumlaKuu));
}
jumla.setText(String.valueOf(JumlaKuu));
itemsNumberView.setText(String.valueOf(ItemsKuu));
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
try something like this.!
final ArrayList<Integer> valuesList = new ArrayList<>();
cou.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
int JumlaKuu =0;
int ItemsKuu =0;
if (dataSnapshot.exists()) {
if (valuesList.size() > 0) {
valuesList.clear();
}
for (DataSnapshot postS : dataSnapshot.getChildren()) {
ProductVar productVar = postS.getValue(ProductVar.class);
JumlaKuu += Integer.parseInt(productVar.getTotal());
ItemsKuu += Integer.parseInt(productVar.getItem());
valuesList.add(Integer.parseInt(productVar.getTotal()));
Log.d("onVil2: ", String.valueOf(JumlaKuu));
}
}
jumla.setText(String.valueOf( getSum(valuesList)));
itemsNumberView.setText(String.valueOf(ItemsKuu));
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
private int getSum(ArrayList<Integer> valuesList) {
int sum = -1;
for (Integer integer : valuesList) {
sum = integer + sum;
}
return sum;
}
Related
Hi I want to read the display data from RecyclerView and make comparison.
This my layout for the activity:
What I want to do is to read all data from RecyclerView and compare with Daily Calorie Suggestion.
After reading all data, I need to make comparisons on how many times the user have taken above, less or sufficient total calories as shown in the "Analysis of Total Calories Consumed of Last 7 Days"
The code:
#Override
protected void onStart() {
Query query = ref.orderByChild("timeStamp").limitToLast(7).endAt(Date);
super.onStart();
if (query != null) {
query .addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
userHighlights = new ArrayList<>();
for (DataSnapshot ds : dataSnapshot.getChildren()) {
userHighlights.add(ds.getValue(HighightsModel.class));
requiredCalorieRef = FirebaseDatabase.getInstance().getReference("Users").child(FirebaseAuth.getInstance().getCurrentUser().getUid());
requiredCalorieRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String userCalorieSuggestion = String.valueOf((dataSnapshot.child("daily calorie").getValue()));
int daily_calorie = Integer.parseInt(userCalorieSuggestion);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
HighlightsAdapter highlightsAdapter = new HighlightsAdapter(userHighlights);
highlightsRV.setAdapter(highlightsAdapter);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(UserNewHighlights.this, databaseError.getMessage(),
Toast.LENGTH_SHORT).show();
}
});
}
}
This is my firebase:
Do I have to write a new code to solve this problem or else? Any help will be much appreciated. Thanks
As #MasoudDarzi mentioned, it's not related to the RecyclerView.
You can try something like this:
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
userHighlights = new ArrayList<>();
for (DataSnapshot ds : dataSnapshot.getChildren()) {
userHighlights.add(ds.getValue(HighightsModel.class));
requiredCalorieRef = FirebaseDatabase.getInstance().getReference("Users").child(FirebaseAuth.getInstance().getCurrentUser().getUid());
requiredCalorieRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String userCalorieSuggestion = String.valueOf((dataSnapshot.child("daily calorie").getValue()));
int daily_calorie = Integer.parseInt(userCalorieSuggestion);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
HighlightsAdapter highlightsAdapter = new HighlightsAdapter(userHighlights);
highlightsRV.setAdapter(highlightsAdapter);
// do calculation here with userHighlights
int countExceeded = 0, countBelow = 0, countSufficient = 0;
for (HighightsModel h : userHighlights) {
if (h.totalCalorie > daily_calorie) {
countExceeded++;
} else if (h.totalCalorie < daily_calorie) {
countBelow++;
} else {
countSufficient++;
}
}
// update your TextView with the count numbers
// todo
}
}
so The brute force solution is to have a for in your data after getting the 7 days average.
for (your 7 days data){
// check if your data is lower or higher than the average
// and store number of higher or lower
}
looking for a better solution?
I have solved my problem by adding another child at History node. Whereby, previously I have only these for History :
but I add new child which is called STATUS, the status is updated from previous activity as seen the pic below:
so what I did for the code is :
private void upDateAnalysisAbove() {
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("History");
DatabaseReference mRef = ref.child(FirebaseAuth.getInstance().getCurrentUser().getUid());
Query mQuery = mRef.orderByChild("status").equalTo("ABOVE").limitToLast(7);
mQuery.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String value = String.valueOf(dataSnapshot.getChildrenCount());
int values = Integer.parseInt(value);
txt_above_output.setText(values + " times(s)");
upDateAnalysisLess(values);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
//LESS
private void upDateAnalysisLess(int values) {
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("History");
DatabaseReference mRef = ref.child(FirebaseAuth.getInstance().getCurrentUser().getUid());
Query mQuery = mRef.orderByChild("status").equalTo("LESS").limitToFirst(7);
mQuery.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String valueLess = String.valueOf(dataSnapshot.getChildrenCount());
int values_Less = Integer.parseInt(valueLess);
if (values_Less == 0){
txt_less_output.setText(values_Less + " times(s)");
}
if (values > values_Less){
int finalCount = values - values_Less ;
txt_less_output.setText(finalCount + " times(s)");
}
if (values <values_Less){
int finalCount = values_Less - values ;
txt_less_output.setText(finalCount + " times(s)");
}
updateSuff();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
//SUFFICIENT
private void updateSuff() {
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("History");
DatabaseReference mRef = ref.child(FirebaseAuth.getInstance().getCurrentUser().getUid());
Query mQuery = mRef.orderByChild("status").equalTo("SUFFICIENT").limitToFirst(7);
mQuery.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String value = String.valueOf(dataSnapshot.getChildrenCount());
int suffValue = Integer.parseInt(value);
if (suffValue == 0) {
txt_sufficient_output.setText(suffValue + " times(s)");
}
if (suffValue != 0){
txt_sufficient_output.setText(suffValue + " times(s)");
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
Here is the output:
credit to this post that helped me a lot, and thanks for those who tried to help me.
I have a problem to do subtract calculation by retrieving data from a Child Nod. As you can see my layout below, what I want to do is to get Remaining Kcal value by calculating Daily Kcal value minus Total Kcal and display the Remaining Kcal to the TextView.
I suspected the calculation for the subtraction part (code below) is not working at all as I tried to put the remainingCount/remainingCalorie value into firebase but nothing happened.
//CALCULATE AND DISPLAY REMAINING CALORIE
private void updateRemainingKcal(final double finalCount) {
DatabaseReference userRecord = FirebaseDatabase.getInstance().getReference();
DatabaseReference userReference = userRecord.child("Users").child(FirebaseAuth.getInstance().getCurrentUser().getUid());
userReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
double remainingCount = 0;
for (DataSnapshot userChild: dataSnapshot.getChildren()) {
for (DataSnapshot recordSnapshot: userChild.getChildren()) {
double userCalorie = Double.valueOf(recordSnapshot.child("daily calorie").getValue(String.class));
remainingCount = userCalorie - finalCount;
userRemainingCalorie.setText((remainingCount +"kcal"));
myHistoryRef = FirebaseDatabase.getInstance().
getReference("History").child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.child(date_record).child("Total Calorie");
Map<String, Object> values = new HashMap<>();
values.put("remainingCalorie", remainingCount);
myHistoryRef.updateChildren(values).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
}
});
}
}
Log.d("TAG", remainingCount + "");
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
});
}
This is relevant code to do this operation, whereby I need to retrieve "daily calorie' from User first, then I can do the substraction daily calorie (Required Kcal) - total calorie consume (Total Kcal) = Remaining Calorie (Remaining Kcal):
//**********************DATABASE REFERENCE FOR USER REQUIRED CALORIE***************************//
requiredCalorieRef = FirebaseDatabase.getInstance().getReference("Users").child(FirebaseAuth.getInstance().getCurrentUser().getUid());
requiredCalorieRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String userCalorieSuggestion = String.valueOf((dataSnapshot.child("daily calorie").getValue()));
userRequiredCalorie.setText((userCalorieSuggestion +"kcal"));
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
//CALCULATE AND DISPLAY TOTAL CALORIE ACCORDING TO DATE
private void updateTotalCalorie(final String date_n) {
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference nameRef = rootRef.child("UsersRecords").child(FirebaseAuth.getInstance().getCurrentUser().getUid()).child(date_record);
nameRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
double count = 0;
for (DataSnapshot foodTypeSnapshot: dataSnapshot.getChildren()) {
for (DataSnapshot recordSnapshot: foodTypeSnapshot.getChildren()) {
double foodCalorie = Double.valueOf(recordSnapshot.child("foodCalorie").getValue(String.class));
count = count + foodCalorie;
userTotalCalorie.setText((count +"kcal"));
myHistoryRef = FirebaseDatabase.getInstance().
getReference("History").child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.child(date_record).child("Total Calorie");
Map<String, Object> values = new HashMap<>();
values.put("totalCalorie", count);
values.put("Date Consume", date_n);
final double finalCount = count;
myHistoryRef.updateChildren(values).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
updateRemainingKcal(finalCount);
}
});
}
}
Log.d("TAG", count + "");
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
});
}
//CALCULATE AND DISPLAY REMAINING CALORIE
private void updateRemainingKcal(final double finalCount) {
DatabaseReference userRecord = FirebaseDatabase.getInstance().getReference();
DatabaseReference userReference = userRecord.child("Users").child(FirebaseAuth.getInstance().getCurrentUser().getUid());
userReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
double remainingCount = 0;
for (DataSnapshot userChild: dataSnapshot.getChildren()) {
for (DataSnapshot recordSnapshot: userChild.getChildren()) {
double userCalorie = Double.valueOf(recordSnapshot.child("daily calorie").getValue(String.class));
remainingCount = userCalorie - finalCount;
userRemainingCalorie.setText((remainingCount +"kcal"));
myHistoryRef = FirebaseDatabase.getInstance().
getReference("History").child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.child(date_record).child("Total Calorie");
Map<String, Object> values = new HashMap<>();
values.put("remainingCalorie", remainingCount);
myHistoryRef.updateChildren(values).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
}
});
}
}
Log.d("TAG", remainingCount + "");
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
});
}
This is my firebase looks like - there is no node of RemainingCalorie at all at History node:
How can I solve this issue despite knowing the problem. I have tried several ways but nothing could help to solve this code problem.
I have solved my own problem. Thank you, finally did it. This is right code for those who have same problem in future:
private void updateRemaining(final int finalCount) {
userDatabase = FirebaseDatabase.getInstance().getReference("Users").child(FirebaseAuth.getInstance().getCurrentUser().getUid());
userDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String user = String.valueOf((dataSnapshot.child("daily calorie").getValue()));
int dailyCalorie = Integer.parseInt(user);
int remainingCalorie = dailyCalorie-finalCount;
userRemainingCalorie.setText((remainingCalorie +"kcal"));
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
throw databaseError.toException();
}
});
}
this is the screen-shot
I am trying to calculate the sum of value of all children in the databse with the name "Price"
below is my code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
mtotal = (TextView) findViewById(R.id.textre);
mda = FirebaseDatabase.getInstance().getReference().child("Cart");
mda.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
int sum = 0;
for (DataSnapshot ds : dataSnapshot.getChildren()) {
Map<String, Object> map = (Map<String, Object>) ds.getValue();
Object price = map.get("Price");
int pvalue = Integer.parseInt(String.valueOf(price));
sum += pvalue;
if (sum<100){
Toast.makeText(getApplicationContext(),"greare",Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(getApplicationContext(),"sorry",Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage());
}
});
as shown in my code if the value obtained from the price nodes is less than 100 then a toast message should appear saying "success". Instead, the app crushes with no message
the image is a view of my firebase database showing the values "Price" I wish to obtain
Try doing this, I think that you are not getting the Price value right
mda.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
int sum = 0;
for (DataSnapshot ds : dataSnapshot.getChildren()) {
int pvalue = ds.child("Price").getValue(Integer.class);
sum += pvalue;
if (sum<100){
Toast.makeText(getApplicationContext(),"greare",Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(getApplicationContext(),"sorry",Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage());
}
});
I want to retrieve the value for each category and then add it to the MPAndroid Pie Chart module that I'm using.
Basically, I want to:
Get value for Communication from month 1
Get value for Communication from month 2
Add the values
Add it to my List Cats with Cats.add(new PieEntry(my_total_value,category_name);
This is what I'm currently implementing for my radar chart but it duplicates each category for each month because it adds a value to the list for each month:
public void setYearRadar(final String date, boolean incexp)
{
final String incexpt;
if(incexp)
{
incexpt="Expense";
}
else
{
incexpt="Income";
}
final DatabaseReference dRef = FirebaseDatabase.getInstance().getReference();
dRef.child("Users")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.child(date)
.addListenerForSingleValueEvent(new ValueEventListener()
{
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
Rcats = new ArrayList<>();
Rlabel = new ArrayList<>();
for (DataSnapshot d: dataSnapshot.getChildren())
{
Query expQuery =
dRef.child("Users")
.child(cAuth.getCurrentUser().getUid())
.child(date)
.child(d.getKey())
.child("Transactions")
.child("Category")
.child(incexpt);
if(expQuery!=null)
{
expQuery.addListenerForSingleValueEvent(new ValueEventListener()
{
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
Float x=0f;
for (DataSnapshot d : dataSnapshot.getChildren())
{
x = x + Float.parseFloat(d.getValue().toString());
}
for (DataSnapshot d : dataSnapshot.getChildren())
{
if (Float.parseFloat(d.getValue().toString()) > 0.0)
{
Rcats.add(new RadarEntry(Float.parseFloat(d.getValue().toString())/x*100, d.getKey())); //Adding value and converting to percentage
Rlabel.add(d.getKey());
}
}
if (!Rcats.isEmpty()&& Rcats.size()>2 && Rlabel.size()>2)
{
initRadarChart(Rcats,Rlabel,date,incexpt);
}
else
{
rc.setVisibility(LinearLayout.GONE);
}
}
#Override
public void onCancelled(DatabaseError databaseError)
{
}
});
}
}
}
#Override
public void onCancelled(DatabaseError databaseError)
{
}
});
}
This is how my Categories look like
This is my whole data structure
And here is the even more messy PieChart class
private void setYearPie(final String date, Boolean incexp)
{
final String incexpt;
if(incexp)
{
incexpt="Expense";
}
else
{
incexpt="Income";
}
final DatabaseReference dRef = FirebaseDatabase.getInstance().getReference();
dRef.child("Users")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.child(date)
.addListenerForSingleValueEvent(new ValueEventListener()
{
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
Ycats = new ArrayList<>();
Ylabel = new ArrayList<>();
for (DataSnapshot d: dataSnapshot.getChildren())
{
Query expQuery =
dRef.child("Users")
.child(cAuth.getCurrentUser().getUid())
.child(date)
.child(d.getKey())
.child("Transactions")
.child("Category")
.child(incexpt);
if(expQuery!=null)
{
expQuery.addListenerForSingleValueEvent(new ValueEventListener()
{
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
for (DataSnapshot d : dataSnapshot.getChildren())
{
if (Float.parseFloat(d.getValue().toString()) > 0.0)
{
Ycats.add(new PieEntry(Float.parseFloat(d.getValue().toString()), d.getKey()));
Ylabel.add(d.getKey());
x = 0f;
}
if (!Ycats.isEmpty())
{
initPieChart(Ycats,Ylabel,date,incexpt);
}
else
{
//pc.setVisibility(LinearLayout.GONE);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError)
{
}
});
}
}
}
#Override
public void onCancelled(DatabaseError databaseError)
{
}
});
}
My expected outcome is that I want to create the final list for each category entered once with values from each month for that category, Eg. if in month 1 food=400 and in month 2 food=800 then I want my final list added as {1200,food}
I'm at my wits end here, and my brain has stopped working, I'd really appreciate any help, thanks.
I'm new at android programming as well as firebase. first of all look at the picture
Details image
In there I want to get all the "cost" part in total(sum). I've created the reference like that
DatabaseReference databaseBazars=firebaseDatabase.getInstance().getReference("BazarList");
now what procedure I can follow to get sum and show it in list view or in a toast message).
I've done this to get all the data from that(BazarList) node . and it perfectly showing on the listview.
databaseBazars.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
bazarList.clear();
for( DataSnapshot ds :dataSnapshot.getChildren()) {
Bazar bazar = ds.getValue(Bazar.class);
bazarList.add(bazar);
}
BazarList adapter = new BazarList(Bazar_Data_Input.this,bazarList);
listViewBazars.setAdapter(adapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
now, how can I get the sum part of the cost. anyone, please help me
here is the Bazar Class
public class Bazar {
String bid;
String date;
String cost;
String name;
String item;
public Bazar(){
}
public Bazar(String bid, String date, String cost, String name,String item) {
this.bid = bid;
this.date = date;
this.cost = cost;
this.name = name;
this.item= item;
}
public String getBid() {
return bid;
}
public String getDate() {
return date;
}
public String getCost() {
return cost;
}
public String getName() {
return name;
}
public String getItem() {
return item;
}
}
To solve this, please use the following code:
databaseBazars.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
bazarList.clear();
Integer total = 0;
for( DataSnapshot ds :dataSnapshot.getChildren()) {
Bazar bazar = ds.getValue(Bazar.class);
Integer cost = Integer.valueOf(bazar.getCost());
total = total + cost;
bazarList.add(bazar);
}
BazarList adapter = new BazarList(Bazar_Data_Input.this,bazarList);
listViewBazars.setAdapter(adapter);
Log.d("TAG", total + "");
}
#Override
public void onCancelled(DatabaseError databaseError) {}
});
The output will be: 59512.
when you have bazarList with items from firebase then simply iterate over list and do sum
databaseBazars.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
bazarList.clear();
for( DataSnapshot ds :dataSnapshot.getChildren()) {
Bazar bazar = ds.getValue(Bazar.class);
bazarList.add(bazar);
}
BazarList adapter = new BazarList(Bazar_Data_Input.this,bazarList);
listViewBazars.setAdapter(adapter);
}
double sum=getSum(); // at this moment your list have results so call getSum to get SUM
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
below is code which will do the trick
private double getSum()
{
double sum;
for( int i = 0; i < bazarList.size(); i++)
{
sum += bazarList.get(i).getCost; // Assuming Bazar class has getCost Method
}
return sum;
}
databaseBazars.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange (DataSnapshot dataSnapshot){
bazarList.clear();
for (DataSnapshot ds : dataSnapshot.getChildren()) {
Bazar bazar = ds.getValue(Bazar.class);
bazarList.add(bazar);
}
// Iterate and add all costs to sum
double sum = 0;
for (Bazar b : bazarList) {
sum += Double.parseDouble(b.getCost())
}
BazarList adapter = new BazarList(Bazar_Data_Input.this, bazarList);
listViewBazars.setAdapter(adapter);
}
#Override
public void onCancelled (DatabaseError databaseError){
}
});
mReference.addValueEventListener(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
if (snapshot.exists()) {
for (i in snapshot.children) {
val item = i.getValue(CartItem::class.java)
cartList!!.add(item!!)
}
var sum = 0.0
for (itm: CartItem in cartList!!) {
sum += itm.itemPrice.toDouble()
}
total_value.text = sum.toString()
//Initialise my adapter
mRecyclerView.adapter = CartItemsAdapter(applicationContext, cartList!!)
}
}
override fun onCancelled(error: DatabaseError) {
}
})