How to read data from RecyclerView and make comparison? - android

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.

Related

Do calculation by retrieving data from Child Node is not working at all in Android Studio/Firebase

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

How to limit retrieve data on firebase realtime Android Studio

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

When running the following code, why does it run 6 times?

I am trying to run this code so that if the statements are true, then a toastMessage should appear but for some reason, it is trying to run the toast 6 times, according to the logs.
When the toast run, it flashes each time it is run. How can I let the toast only run once?
Even If I replace the toast with an alert, I have to press OK 6 times before it will dismiss.
Log Result:
checkForIOSRequests/riderId: xmmEHZJkOXOJbLXdCQjuZvpS80j1
checkForIOSRequests/riderId: xmmEHZJkOXOJbLXdCQjuZvpS80j1
checkForIOSRequests/riderId: xmmEHZJkOXOJbLXdCQjuZvpS80j1
checkForIOSRequests/riderId: xmmEHZJkOXOJbLXdCQjuZvpS80j1
checkForIOSRequests/riderId: xmmEHZJkOXOJbLXdCQjuZvpS80j1
checkForIOSRequests/riderId: xmmEHZJkOXOJbLXdCQjuZvpS80j1
requestToastMessage
requestToastMessage
requestToastMessage
requestToastMessage
requestToastMessage
requestToastMessage
checkForIOSRequests
iosRequests.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
riderId = ds.getKey();
Log.e(TAG, "checkForIOSRequests/riderId: " + riderId);
iosRequests.child(riderId).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.child("status").getValue() != null) {
if (dataSnapshot.child("isIOSRider").getValue() != null) {
String isIOSRider = (String) dataSnapshot.child("isIOSRider").getValue();
String onlineStatus = (String) dataSnapshot.child("status").getValue();
if (isIOSRider.equals("true") && onlineStatus.equals("requested")) {
requestToastMessage();
}
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) { }
});
EDIT
DatabaseReferene rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference iosRequests = rootRef.child("RideRequests");
EDIT 2
When I run the following code, it runs it 6 times like in the Log Result
iosRequests.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
riderId = ds.getKey();
iosRequests.child(riderId).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
int size = (int) dataSnapshot.getChildrenCount();
Log.e(TAG, "children count = " + size);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Log Result
I just don't know why are you using two database call when you can do filter using one database query.
Just use below query to filter out all IOSRider using isIOSRider key.
DatabaseReferene rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference iosRequests = rootRef.child("RideRequests");
Query queryIOSRiders = iosRequests.orderByChild("isIOSRider").equalTo(true);
// Keep in mind that, if you are storing boolean value in database then only use true in equalTo(...). i.e. equalTo(true)
// Else use true covered with quotes. i.e. equalTo("true")
And make call of database,
queryIOSRiders. addListenerForSingleValueEvent(...)
This query returns all iOS riders list, so then after you need to put simple if-else braces to filter out suitable riders.
For example, your final result handling code should be like,
queryIOSRiders.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.getValue()!= null) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
if (ds.child("status").getValue() != null) {
String onlineStatus = (String) ds.child("status").getValue();
if (onlineStatus.equals("requested")) {
requestToastMessage();
}
}
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) { }
});

How to successfully calculate value from a child in firebase database

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());
}
});

Need help regarding a firebase Query to append the values of a key from multiple nodes of the same child

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.

Categories

Resources