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());
}
});
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 want to compare text with data from firebase. Below is my code and it reads name only from ing01. but actually i want it to read from all ingredient data, not only ing01. Please help me, thank you.
final String dataCompare=sb.toString();//.replaceAll("\\s+","");
databaseReference = firebaseDatabase.getInstance().getReference().child("ingredients");//.child("ing01").child("iName");
databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot ds: dataSnapshot.getChildren()){
String iName = ds.child("iName").getValue(String.class);
if(dataCompare.equals(iName)){
mResultEt.setText(dataCompare);
mStatusEt.setText("OK");
mStatusEt.setTextColor(Color.GREEN);
}
else{
mResultEt.setText(dataCompare);
mStatusEt.setText("Not OK");
mStatusEt.setTextColor(Color.RED);
}
}
Check this:
FirebaseDatabase.getInstance().getReference().child("ingredients").addListenerForSingleValueEvent(
new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot childSnapshot : dataSnapshot.getChildren()) {
String iName = childSnapshot.child("iName").getValue(String.class);
//Implement your logic here
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
}
);
Here you will get all the ingredients and through iteration you get the iName.
But According your implementation logic. It's useless to get all the ingredients, rather you can get the specific ingredient matching your compare query. Try like below:
FirebaseDatabase.getInstance().getReference().child("ingredients").orderByChild("iName").equalTo(dataCompare).addListenerForSingleValueEvent(
new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.hasChildren()) {
mResultEt.setText(dataCompare);
mStatusEt.setText("OK");
mStatusEt.setTextColor(Color.GREEN);
} else {
mResultEt.setText(dataCompare);
mStatusEt.setText("Not OK");
mStatusEt.setTextColor(Color.RED);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
}
);
Instead of firebaseDatabase.getInstance().getReference().child("ingredients").child("ing01").child("iName");, use firebaseDatabase.getInstance().getReference().child("ingredients"); for getting all ingredients
you can used a third party library like: Angularfire here is there official link: https://github.com/angular/angularfire
final String dataCompare=sb.toString();
databaseReference = firebaseDatabase.getInstance().getReference().child("ingredients");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String iName1 = dataSnapshot.child("ing01").child("iName");
String iName2 = dataSnapshot.child("ing02").child("iName");
//now here you can compare both the iName values with the dataCompare object.
}
}
**** EDIT ****
final String dataCompare=sb.toString();
Log.d("DataCompare: ", dataCompare);
databaseReference = firebaseDatabase.getInstance().getReference().child("ingredients");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.getChildren() == null) {
Log.d(TAG, "onDataChange: snapshot has no children");
} else {
int i = 1;
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String iName = ds.child("ing0" + i++).child("iName").getValue();
// if this doesn't work try this --
// String iName = ds.child("iName").getValue();
Log.d(TAG, "name value: " + iName);
if (iName.equals(dataCompare)) {
Log.d(TAG, "onDataChange: string equals");
} else {
Log.d(TAG, "onDataChange: strings are not equal");
}
}
}
}
}
Inside the onDataChange() method I wrote :-
String iName = ds.child("ing0" + i++).child("iName").getValue();
here we are reading the child "ing01" (in the first iteration of the loop) of the datasnapshot which is currently at "ingredients", and then we read "iName" and its value into iName string object.
for each loop will do this for all the children of the dataSnapshot which means for all the data you have in your firebase database.
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 want to ask about how to limit retrieve data in Android Firebase. Here is my code:
private void lookingforHelp(){
DatabaseReference dbref = FirebaseDatabase.getInstance().getReference("Locations");
dbref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot ds: dataSnapshot.getChildren()){
int limitUser = 0;
ModelUsersLocation mUserLoct = ds.getValue(ModelUsersLocation.class);
LatLng yourLatLng = new LatLng(latitude_user, longitude_user);
LatLng polisiLatLng = new LatLng(mUserLoct.getLatitude(), mUserLoct.getLongitude());
if (mUserLoct.getPengguna().equals("polisi")){
if (SphericalUtil.computeDistanceBetween(yourLatLng, polisiLatLng) < 700) {
if (limitUser <= 5){
if (mUserLoct.getJangkauan().isEmpty()) {
DatabaseReference dbref = FirebaseDatabase.getInstance().getReference("Locations").child(mUserLoct.getUser().getUid());
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("jangkauan", fuser.getUid());
dbref.updateChildren(hashMap).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
writeNewOrder();
}
});
}
}
}
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
I tried to retrieve data that i want is only less than 5 users, using int limitUser = 0; and it's still not working to retrieve data only less than 5 users.
PROBLEM SOLVED, I try to create markeroptions and make it into invisible, and then add it into arraylist, if (markers.size() <= 5) {do something}
thank u guys for your help btw i really apreciate it :))
public MutableLiveData<ArrayList<Vendor>> getVendorsByLimit(int limit) {
ArrayList<Vendor> arrayList = new ArrayList<>();
Query query = FirebaseDatabase.getInstance().getReference().child("VENDOR_NODE").limitToLast(limit);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.getChildrenCount() > 0) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
if (snapshot.getChildrenCount() > 0) {
//String value = (String) snapshot.getValue(); //Get all child data
//OR
//String singleValue = (String) snapshot.child("fullName").getValue(); //Get single child data
Vendor model = snapshot.getValue(Vendor.class);
String key = snapshot.getKey();
arrayList.add(model);
}
}
data.setValue(arrayList);
} else {
data.setValue(null);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.e(TAG, "" + databaseError.getMessage());
data.setValue(null);
}
});
}
Query query = FirebaseDatabase.getInstance().getReference().child("VENDOR_NODE").limitToLast(limit);
You can sort them by using timeStamp like
-----------------------------------------
FirebaseDatabase.getInstance().getReference()
.child("Conversation").child(conversationID)
.limitToLast(100)
.orderByChild("timestamp")
.startAt(dateToStart) // pass timestamp from when you want to start filtering
.endAt(dateToEnd); // pass timestamp till when you want to apply filtering
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.