如何使用 MSSQL 数据库中的数据填充 MPAndroid 饼图?

How to populate MPAndroid Pie Chart with data from MSSQL Database?

我是 Android 编程新手,我想用我的 MSSQL 数据库中的值填充我的饼图。

谁能帮帮我,我已经被困了好久了。

我想在饼图中填充的值是 'expenses_amount' 和 'expenses category',它们位于我的 'Expenses' table.

到目前为止我已经得到了这个,但是它不起作用

        final Spinner budgetNameSpinner = (Spinner) getView().findViewById(R.id.BudgetNameSpinner);
        String chosenBudget = budgetNameSpinner.getSelectedItem().toString();
        String s = getActivity().getIntent().getExtras().getString("UserLoginDetails");
        if (DbConnectionClass.connection == null) {
            new DbConnectionClass().connectDB();
        }
        if (DbConnectionClass.connection != null) {
            Statement statement = null;
            try {
                statement = DbConnectionClass.connection.createStatement();
                String query = "SELECT expenses_category, SUM(expenses_amount) AS TotalExpenses FROM EXPENSES_T LEFT JOIN USERLOGINDETAILS_T ON EXPENSES_T.username_id_fk = USERLOGINDETAILS_T.user_id LEFT JOIN BUDGET_T ON EXPENSES_T.budget_id_fk = BUDGET_T.budget_id WHERE USERLOGINDETAILS_T.user_name = '" + s + "' AND BUDGET_T.budget_name = '" + chosenBudget + "' GROUP BY expenses_category";
                ResultSet rs = statement.executeQuery(query);
                //ArrayList<PieEntry> data = new ArrayList<>();
                List<PieEntry> pieEntries = new ArrayList<>();
                int size = 0;
                if (rs != null) {
                    rs.last();
                    size = rs.getRow();
                }
                for (int i = 0; i < size; i++) {
                    String ExpenseCategories = rs.getString("expenses_category");
                    Float ExpenseAmount = rs.getFloat("TotalExpenses");
                    Float eC[] = {ExpenseAmount};
                    String eA[] = {ExpenseCategories};
                    pieEntries.add(new PieEntry(eC[i], eA[i]));
                }
                    PieDataSet dataSet = new PieDataSet(pieEntries, "Expenses");
                    PieData data = new PieData(dataSet);
                    //get chart
                    PieChart chart = (PieChart) getView().findViewById(R.id.piechart);
                    dataSet.setColors(ColorTemplate.COLORFUL_COLORS); //set color
                    chart.setData(data);
                    chart.animateY(1000); //animate pie chart
                    chart.invalidate();


            } catch (Exception e) {

            }

上面的代码是我试图从我从 Youtube 获得的一个简单代码进行修改的。

好吧,我从 mssql 中绘制了一个饼图,但我在异步上执行请求,然后我调用方法 SetupData() 来设置视图中的数据。

查询的异步代码段

 String query = "your query";
                Statement stmt = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
                        ResultSet.CONCUR_READ_ONLY);
                ResultSet rs = stmt.executeQuery(query);
                sumaporcentajes = 0;
                while (rs.next()) {
                    EntDataTorta item = new EntDataTorta(
                            rs.getString("Categoria"),
                            rs.getFloat("Cantidad")
                    );
                    listaTorta.add(item);

                }

然后在我的activity我有这个方法。

public void setUpData() {
    //used by async on finished
    PieChart piechart = findViewById(R.id.pieChart);
    lDatos.clear();
    lDatos.removeAll(lDatos);
    for (int i = 0; i < lItems.size(); i++) {
        lDatos.add(new PieEntry(lItems.get(i).getPorcentaje(), lItems.get(i).getCategoria()));
    }
    //Creo un dataset y se lo seteo al gráfico
    PieDataSet set = new PieDataSet(lDatos, "");
    PieData data = new PieData(set);
    piechart.setCenterTextTypeface(Typeface.DEFAULT_BOLD);
    Legend legend = piechart.getLegend();
    legend.setEnabled(true);
    DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyyMMdd").withLocale(Locale.CANADA);
    sDesde = formatter.withLocale(Locale.CANADA).parseLocalDate(sDesde).toString();
    sHasta = formatter.parseLocalDate(sHasta).toString();

    if (bHistorico) {
        sHasta = LocalDate.now().toString();
        bHistorico = false;
    }
    piechart.setCenterText("Cantidad de Consultas: " + sumaporcentajes);
    piechart.getDescription().setText("Periodo de tiempo sDesde: " + sDesde + "  sHasta " + LocalDate.now().minusMonths(meses).dayOfMonth().withMaximumValue());
    piechart.getDescription().setTextColor(0xFFFFFFFF);
    piechart.getDescription().setTextSize(12f);
    set.setColors(ColorTemplate.COLORFUL_COLORS);
    set.setValueFormatter(new MyValueFormatter());
    piechart.setData(data);
    piechart.invalidate(); // refresh
}

希望这些片段对您有所帮助。