package com.example.test_001;
import androidx.appcompat.app.AppCompatActivity;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import java.util.Calendar;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.formatter.IndexAxisValueFormatter;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.example.test_001.db.AccountingDBHelper;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeSet;
import android.util.Log;
public class statisticsActivity extends AppCompatActivity {
private static final String TAG = "statisticsActivity";
private LineChart lineChart;
private PieChart pieChart;
private int selectedYear, selectedMonth, selectedDay;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
setContentView(R.layout.activity_statistics);
lineChart = findViewById(R.id.lineChart);
pieChart = findViewById(R.id.pieChart);
DateIsToday(); // 设置为今天
refreshAllCharts(selectedYear, selectedMonth); // 加载默认数据
Button button = findViewById(R.id.backb);
button.setOnClickListener(v -> startActivity(new Intent(statisticsActivity.this, MainActivity.class)));
Button button2 = findViewById(R.id.setb);
button2.setOnClickListener(v -> showDatePickerDialog());
}
private void DateIsToday() {
Calendar calendar = Calendar.getInstance();
selectedYear = calendar.get(Calendar.YEAR);
selectedMonth = calendar.get(Calendar.MONTH);
selectedDay = calendar.get(Calendar.DAY_OF_MONTH);
}
private void showDatePickerDialog() {
DatePickerDialog dialog = new DatePickerDialog(this,
(view, year, monthOfYear, dayOfMonth) -> {
selectedYear = year;
selectedMonth = monthOfYear;
selectedDay = dayOfMonth;
refreshAllCharts(year, monthOfYear);
},
selectedYear, selectedMonth, selectedDay);
dialog.getDatePicker().setMaxDate(System.currentTimeMillis());
dialog.show();
}
private void refreshAllCharts(int year, int month) {
updateLineChart(year, month);
updatePieChart(year, month, selectedDay);
}
// 更新折线图:按天 + 类型汇总
private void updateLineChart(int year, int month) {
AccountingDBHelper dbHelper = new AccountingDBHelper(this);
SQLiteDatabase db = dbHelper.getReadableDatabase();
String query = "SELECT date, type, SUM(amount) AS total_amount FROM transactions " +
"WHERE strftime('%Y-%m', date) = ? GROUP BY date, type";
Cursor cursor = db.rawQuery(query, new String[]{String.format("%d-%02d", year, month + 1)});
Map<String, Float> incomeMap = new HashMap<>();
Map<String, Float> expenseMap = new HashMap<>();
if (cursor != null && cursor.moveToFirst()) {
do {
String date = cursor.getString(cursor.getColumnIndexOrThrow("date"));
String type = cursor.getString(cursor.getColumnIndexOrThrow("type"));
float amount = cursor.getFloat(cursor.getColumnIndexOrThrow("total_amount"));
String shortDate = date.substring(5); // MM-dd
if ("收入".equals(type)) {
// 替代 getOrDefault 的写法
incomeMap.put(shortDate, incomeMap.containsKey(shortDate) ? incomeMap.get(shortDate) + amount : amount);
} else if ("支出".equals(type)) {
expenseMap.put(shortDate, expenseMap.containsKey(shortDate) ? expenseMap.get(shortDate) + amount : amount);
}
} while (cursor.moveToNext());
cursor.close();
}
ArrayList<String> xLabels = new ArrayList<>(new TreeSet<>(mergeKeys(incomeMap.keySet(), expenseMap.keySet())));
ArrayList<Entry> incomeEntries = new ArrayList<>();
ArrayList<Entry> expenseEntries = new ArrayList<>();
for (int i = 0; i < xLabels.size(); i++) {
String label = xLabels.get(i);
float incomeValue = incomeMap.containsKey(label) ? incomeMap.get(label) : 0f;
float expenseValue = expenseMap.containsKey(label) ? expenseMap.get(label) : 0f;
incomeEntries.add(new Entry(incomeValue, i));
expenseEntries.add(new Entry(expenseValue, i));
}
LineDataSet incomeSet = new LineDataSet(incomeEntries, "收入");
incomeSet.setColor(Color.GREEN);
incomeSet.setCircleColor(Color.GREEN);
LineDataSet expenseSet = new LineDataSet(expenseEntries, "支出");
expenseSet.setColor(Color.RED);
expenseSet.setCircleColor(Color.RED);
lineChart.setData(new LineData(incomeSet, expenseSet));
lineChart.getXAxis().setValueFormatter(new IndexAxisValueFormatter(xLabels));
lineChart.getXAxis().setLabelCount(xLabels.size(), true);
lineChart.getXAxis().setPosition(XAxis.XAxisPosition.BOTTOM);
lineChart.animateY(1000);
lineChart.invalidate();
}
// 更新饼图:当天数据
private void updatePieChart(int year, int month, int day) {
String formattedDate = String.format("%d-%02d-%02d", year, month + 1, day);
AccountingDBHelper dbHelper = new AccountingDBHelper(this);
SQLiteDatabase db = dbHelper.getReadableDatabase();
Cursor cursor = db.query(
AccountingDBHelper.TABLE_TRANSACTIONS,
new String[]{"category", "SUM(amount) AS total_amount"},
"date = ?",
new String[]{formattedDate},
"category",
null,
null
);
ArrayList<PieEntry> entries = new ArrayList<>();
if (cursor != null && cursor.moveToFirst()) {
do {
String category = cursor.getString(cursor.getColumnIndexOrThrow("category"));
float amount = cursor.getFloat(cursor.getColumnIndexOrThrow("total_amount"));
entries.add(new PieEntry(amount, category));
} while (cursor.moveToNext());
cursor.close();
}
if (entries.isEmpty()) {
entries.add(new PieEntry(1f, "无数据"));
}
PieDataSet dataSet = new PieDataSet(entries, "分类统计");
dataSet.setColors(ColorTemplate.MATERIAL_COLORS);
dataSet.setSliceSpace(2f);
PieData data = new PieData(dataSet);
data.setValueTextSize(12f);
pieChart.setData(data);
pieChart.getDescription().setEnabled(false);
pieChart.setCenterText("分类统计");
pieChart.invalidate();
}
private java.util.Set<String> mergeKeys(java.util.Set<String> set1, java.util.Set<String> set2) {
java.util.Set<String> merged = new TreeSet<>();
merged.addAll(set1);
merged.addAll(set2);
return merged;
}
}
现在的问题就是折线图x轴没东西,应该是对应的日期(只有月日的格式)y轴数据应该是根据最大钱数变化的不是默认的这种
最新发布