0% found this document useful (0 votes)
89 views

Piechart Code

The document describes how to create a pie chart showing the amount spent on different categories within a specific date range using data from Firebase. It explains how to retrieve and filter the data based on the date range, calculate the total amount spent for each category, and use an Android charting library to create and display the pie chart. Sample code is provided to retrieve data from Firebase, filter by date, calculate category totals, and generate the pie chart.

Uploaded by

Ketan Dhumal
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
89 views

Piechart Code

The document describes how to create a pie chart showing the amount spent on different categories within a specific date range using data from Firebase. It explains how to retrieve and filter the data based on the date range, calculate the total amount spent for each category, and use an Android charting library to create and display the pie chart. Sample code is provided to retrieve data from Firebase, filter by date, calculate category totals, and generate the pie chart.

Uploaded by

Ketan Dhumal
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

in my android project i used firebse as a database and it contains fild like ammount,category,date.

i
want to show piechart of ammount spent on different category in within spacific date range

To show a pie chart of the amount spent on different categories within a specific date range, you can
follow these steps:

Retrieve data from Firebase: You will need to retrieve data from Firebase that contains the amount
spent, category, and date. You can use Firebase Realtime Database or Firebase Firestore for this
purpose.

Filter data based on date range: Once you have retrieved the data, you will need to filter it based on
the date range selected by the user. You can do this by querying the database to retrieve only those
records that fall within the selected date range.

Calculate the total amount spent for each category: For each category, you will need to calculate the
total amount spent. You can do this by iterating through the filtered data and summing up the
amounts for each category.

Create a Pie Chart: You can use a library like MPAndroidChart to create a Pie Chart. You will need to
provide it with the data for each category and the corresponding amount spent.

Here's some sample code to get you started:

java

Copy code

// Retrieve data from Firebase

FirebaseDatabase database = FirebaseDatabase.getInstance();

DatabaseReference myRef = database.getReference("expenses");

// Filter data based on date range

Query query = myRef.orderByChild("date").startAt(startDate).endAt(endDate);

// Calculate the total amount spent for each category

query.addValueEventListener(new ValueEventListener() {

@Override
public void onDataChange(DataSnapshot dataSnapshot) {

Map<String, Double> categoryAmounts = new HashMap<>();

for (DataSnapshot expenseSnapshot : dataSnapshot.getChildren()) {

Expense expense = expenseSnapshot.getValue(Expense.class);

if (!categoryAmounts.containsKey(expense.getCategory())) {

categoryAmounts.put(expense.getCategory(), expense.getAmount());

} else {

Double currentAmount = categoryAmounts.get(expense.getCategory());

categoryAmounts.put(expense.getCategory(), currentAmount + expense.getAmount());

// Create Pie Chart

PieChart pieChart = (PieChart) findViewById(R.id.pie_chart);

List<PieEntry> entries = new ArrayList<>();

for (Map.Entry<String, Double> entry : categoryAmounts.entrySet()) {

entries.add(new PieEntry(entry.getValue().floatValue(), entry.getKey()));

PieDataSet dataSet = new PieDataSet(entries, "Amount spent on different categories");

PieData data = new PieData(dataSet);

pieChart.setData(data);

pieChart.invalidate();

@Override

public void onCancelled(DatabaseError databaseError) {

Log.w(TAG, "loadPost:onCancelled", databaseError.toException());

});

Note: This code assumes that you have created an Expense class that contains the fields amount,
category, and date. You will also need to replace R.id.pie_chart with the ID of the PieChart view in
your layout file.
Ketan Dhumal

my dates are stored in "02/12/2001" format

If your dates are stored in the "MM/dd/yyyy" format (e.g., "02/12/2001"), you can still filter the data
based on a date range using Firebase Realtime Database or Firebase Firestore. You will just need to
convert the date strings to a format that can be compared as a numerical value.

One way to do this is to convert the dates to Unix timestamps, which represent the number of
seconds that have elapsed since January 1, 1970. You can then use these timestamps to compare the
dates as numerical values.

Here's some sample code to get you started:

java

Copy code

// Convert date strings to Unix timestamps

SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");

Date startDateObj = dateFormat.parse(startDate);

Date endDateObj = dateFormat.parse(endDate);

long startTime = startDateObj.getTime() / 1000;

long endTime = endDateObj.getTime() / 1000;

// Filter data based on Unix timestamps

Query query = myRef.orderByChild("timestamp").startAt(startTime).endAt(endTime);

Note: This code assumes that you have added a field called timestamp to your data model, which
represents the Unix timestamp of the date. You will need to update your data model and database
to include this field. You can calculate the Unix timestamp of a date using the getTime() method of a
Date object, as shown in the code above.
Ketan Dhumal

but dates are not in timestamp format in fire base database

If your dates are not stored in Unix timestamp format in Firebase, you can still filter your data based
on the date range by converting the dates to a comparable format. One way to do this is to convert
the date strings to a Date object and compare them using the compareTo() method.

Here's some sample code to get you started:

java

Copy code

// Convert date strings to Date objects

SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");

Date startDateObj = dateFormat.parse(startDate);

Date endDateObj = dateFormat.parse(endDate);

// Filter data based on Date objects

Query query =
myRef.orderByChild("date").startAt(startDateObj.getTime()).endAt(endDateObj.getTime());

This code converts the startDate and endDate strings to Date objects using a SimpleDateFormat
object. It then uses the getTime() method to convert the Date objects to Unix timestamps, which can
be compared numerically. Finally, it filters the data based on the Unix timestamps using the startAt()
and endAt() methods of the Query object.

Note that this approach assumes that all of your date strings are in the same format
("MM/dd/yyyy"). If your dates are in a different format, you will need to update the
SimpleDateFormat pattern accordingly. Also note that this approach may not be as efficient as using
Unix timestamps if you have a large amount of data, since it requires converting each date string to a
Date object.
Ketan Dhumal

can you merge above code with following code // Retrieve data from Firebase

FirebaseDatabase database = FirebaseDatabase.getInstance();

DatabaseReference myRef = database.getReference("expenses");

// Filter data based on date range

Query query = myRef.orderByChild("date").startAt(startDate).endAt(endDate);

// Calculate the total amount spent for each category

query.addValueEventListener(new ValueEventListener() {

@Override

public void onDataChange(DataSnapshot dataSnapshot) {

Map<String, Double> categoryAmounts = new HashMap<>();

for (DataSnapshot expenseSnapshot : dataSnapshot.getChildren()) {

Expense expense = expenseSnapshot.getValue(Expense.class);

if (!categoryAmounts.containsKey(expense.getCategory())) {

categoryAmounts.put(expense.getCategory(), expense.getAmount());

} else {

Double currentAmount = categoryAmounts.get(expense.getCategory());

categoryAmounts.put(expense.getCategory(), currentAmount + expense.getAmount());

// Create Pie Chart

PieChart pieChart = (PieChart) findViewById(R.id.pie_chart);

List<PieEntry> entries = new ArrayList<>();

for (Map.Entry<String, Double> entry : categoryAmounts.entrySet()) {

entries.add(new PieEntry(entry.getValue().floatValue(), entry.getKey()));

PieDataSet dataSet = new PieDataSet(entries, "Amount spent on different categories");

PieData data = new PieData(dataSet);


pieChart.setData(data);

pieChart.invalidate();

@Override

public void onCancelled(DatabaseError databaseError) {

Log.w(TAG, "loadPost:onCancelled", databaseError.toException());

});

Sure, here's the merged code that filters the data based on the date range before calculating the
total amount spent for each category and creating the pie chart:

java

Copy code

// Retrieve data from Firebase

FirebaseDatabase database = FirebaseDatabase.getInstance();

DatabaseReference myRef = database.getReference("expenses");

// Filter data based on date range

SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");

Date startDateObj = dateFormat.parse(startDate);

Date endDateObj = dateFormat.parse(endDate);

Query query =
myRef.orderByChild("date").startAt(startDateObj.getTime()).endAt(endDateObj.getTime());

// Calculate the total amount spent for each category

query.addValueEventListener(new ValueEventListener() {

@Override

public void onDataChange(DataSnapshot dataSnapshot) {

Map<String, Double> categoryAmounts = new HashMap<>();

for (DataSnapshot expenseSnapshot : dataSnapshot.getChildren()) {

Expense expense = expenseSnapshot.getValue(Expense.class);


if (!categoryAmounts.containsKey(expense.getCategory())) {

categoryAmounts.put(expense.getCategory(), expense.getAmount());

} else {

Double currentAmount = categoryAmounts.get(expense.getCategory());

categoryAmounts.put(expense.getCategory(), currentAmount + expense.getAmount());

// Create Pie Chart

PieChart pieChart = (PieChart) findViewById(R.id.pie_chart);

List<PieEntry> entries = new ArrayList<>();

for (Map.Entry<String, Double> entry : categoryAmounts.entrySet()) {

entries.add(new PieEntry(entry.getValue().floatValue(), entry.getKey()));

PieDataSet dataSet = new PieDataSet(entries, "Amount spent on different categories");

PieData data = new PieData(dataSet);

pieChart.setData(data);

pieChart.invalidate();

@Override

public void onCancelled(DatabaseError databaseError) {

Log.w(TAG, "loadPost:onCancelled", databaseError.toException());

});

Note that this code assumes that you have defined a class called Expense that represents the
structure of your Firebase data. You will need to define this class and make sure it has fields for the
amount, category, and date. If you have not done this yet, you can define the class as follows:

java

Copy code

public class Expense {


private double amount;

private String category;

private String date;

public Expense() {}

public Expense(double amount, String category, String date) {

this.amount = amount;

this.category = category;

this.date = date;

public double getAmount() {

return amount;

public void setAmount(double amount) {

this.amount = amount;

public String getCategory() {

return category;

public void setCategory(String category) {

this.category = category;

public String getDate() {

return date;

}
public void setDate(String date) {

this.date = date;

This class has three fields (amount, category, and date) and getters and setters for each field. You
can modify the class as needed to match the structure of your Firebase data.

Regenerate response

You might also like