PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, April 23, 2022

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

 April 23, 2022     android, java, mpandroidchart, pie-chart, sql-server     No comments   

Issue

I'm new to Android Programming and I want to populate my pie chart with values from my MSSQL Database.

Can someone please help me out, I've been stuck for quite awhile now.

The values I want to populate in my Pie Chart are 'expenses_amount' and 'expenses category' which are under my 'Expenses' table.

I've gotten this so far, but it doesn't work

        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) {

            }

The code above was me attempting to modify from a simple code that I gotten from Youtube.


Solution

Well I pouplate a piechart from mssql, but I do the request on an async and then I call a method SetupData() to set the data in the view.

Async Snippet of query

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

                }

Then in my activity i have this method.

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
}

I hope these snippets helps you.



Answered By - Joaquín
Answer Checked By - Terry (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing