PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label mpandroidchart. Show all posts
Showing posts with label mpandroidchart. Show all posts

Tuesday, November 29, 2022

[FIXED] How to change position in MPAndroidChart PieChart color indicator

 November 29, 2022     indicator, mpandroidchart, pie-chart     No comments   

Issue

I am working on MPAndroidChart and I want to change position of PieChart color indicator.

<com.github.mikephil.charting.charts.PieChart
    android:id="@+id/chart"
    android:layout_width="200dp"
    android:layout_height="200dp"
    android:layout_gravity="center" />

When i set android:layout_width="200dp" and android:layout_height="200dp" It apply height and width whole view.

I want to only make distance between PieChart and its color indicator. Don't want to overlap indicator on PieChart View

enter image description here

enter image description here


Solution

<com.github.mikephil.charting.charts.PieChart
        android:id="@+id/chart1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

Legend l = mChart.getLegend();
        l.setPosition(LegendPosition.LEFT_OF_CHART);
        l.setXEntrySpace(7f);
        l.setYEntrySpace(5f);
        l.setYOffset(0f);

OR

Legend l = mChart.getLegend();
        l.setPosition(LegendPosition.RIGHT_OF_CHART_CENTER);
        l.setXEntrySpace(7f);
        l.setYEntrySpace(5f);
        l.setYOffset(0f);


Answered By - Shailesh Lakum
Answer Checked By - Timothy Miller (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Saturday, April 23, 2022

[FIXED] How to remove bottom space in a pie chart?

 April 23, 2022     android, android-layout, mpandroidchart, pie-chart     No comments   

Issue

I am using Pie Chart in my application, Right now Pie Chart is displaying properly ,only issue is getting space at bottom of Pie Chart. Following is code of Pie Chart and output what I want and What I am trying to get.

Using this library for piechart

https://github.com/PhilJay/MPAndroidChart

 PieChart pieChart = (PieChart) view.findViewById(R.id.fragment_chart);
        pieChart.setUsePercentValues(true);
        Display display = getActivity().getWindowManager().getDefaultDisplay();
        int height = display.getHeight();  // deprecated

        int offset = (int)(height * 0.65); /* percent to move */

       /* RelativeLayout.LayoutParams rlParams =
                (RelativeLayout.LayoutParams)pieChart.getLayoutParams();
        rlParams.setMargins(0, 0, 0, -offset);
        pieChart.setLayoutParams(rlParams);*/
        // IMPORTANT: In a PieChart, no values (Entry) should have the same
        // xIndex (even if from different DataSets), since no values can be
        // drawn above each other.
        ArrayList<PieEntry> yvalues = new ArrayList<PieEntry>();
        yvalues.add(new PieEntry(8f, 0));
        yvalues.add(new PieEntry(15f, 1));
        yvalues.add(new PieEntry(12f, 2));


        PieDataSet dataSet = new PieDataSet(yvalues, "Reward Points");

        ArrayList<String> xVals = new ArrayList<String>();

        xVals.add("January");
        xVals.add("February");
        xVals.add("March");
        xVals.add("April");
        xVals.add("May");
        xVals.add("June");

        PieData data = new PieData( dataSet);

        data.setValueFormatter(new PercentFormatter());
        pieChart.setData(data);
        //pieChart.setDescription("This is Pie Chart");

        pieChart.setBackgroundColor(Color.TRANSPARENT);
        pieChart.setHoleColor(Color.WHITE);
        pieChart.setTransparentCircleColor(Color.WHITE);
        pieChart.setTransparentCircleAlpha(0);
        pieChart.setHoleRadius(18f);
        pieChart.setDrawCenterText(true);
        pieChart.isRotationEnabled();
        pieChart.isHighlightPerTapEnabled();
        pieChart.setCenterTextOffset(0f,-20f);
        pieChart.setEntryLabelColor(Color.WHITE);
        pieChart.setEntryLabelTypeface(Typeface.DEFAULT);
        pieChart.setEntryLabelTextSize(16f);
        pieChart.setTransparentCircleRadius(11f);

        pieChart.setDrawHoleEnabled(true);


        pieChart.setMaxAngle(180.0f);
        pieChart.setRotationAngle(180.0f);
        pieChart.setCenterTextSize(30);

        dataSet.setColors(ColorTemplate.VORDIPLOM_COLORS);
        data.setValueTextSize(13f);

        data.setValueTextColor(Color.DKGRAY);
        //pieChart.setOnChartValueSelectedListener(getActivity());

        pieChart.animateY(1400, Easing.EaseInOutQuad);

Expected Output

Out

Getting Output

enter image description here


Solution

Use below code.

pieChart.setHoleRadius(64f);//18f
pieChart.setCenterTextSize(10);//30
pieChart.setCenterText("Reward Points: 150");//new line

pieChart.setExtraOffsets(5f,0f,10f,-100f);

Adjust value of bottom offset in setExtraOffsets(in above code value -100f) in order to adjust space.enter image description here



Answered By - Pravin Divraniya
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How Can I get text from piechart

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

Issue

I have use MP Android pie chart lib, here I am showing text into piechart , I also want to get this text out side the chart.

I want to get the text (xvals) when clicked on pie chart. Let say when I click on a part of pie chart then it should get text value of it(eg, uber,paytm)

Code

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    PieChart pieChart = (PieChart) findViewById(R.id.piechart);
        pieChart.setUsePercentValues(true);

        datatext = (TextView)findViewById(R.id.datatext);

        datatitle = (TextView)findViewById(R.id.datatitle);

        // IMPORTANT: In a PieChart, no values (Entry) should have the same
    // xIndex (even if from different DataSets), since no values can be
    // drawn above each other.
    ArrayList<Entry> yvalues = new ArrayList<Entry>();
        yvalues.add(new Entry(24f, 0));
        yvalues.add(new Entry(15f, 1));
        yvalues.add(new Entry(19f, 2));
        yvalues.add(new Entry(22f, 3));
        yvalues.add(new Entry(20f, 4));
        //yvalues.add(new Entry(17f, 5));

    PieDataSet dataSet = new PieDataSet(yvalues, "Balances");

    ArrayList<String> xVals = new ArrayList<String>();

        xVals.add("Monthly Expenses");
        xVals.add("Phonepe");
        xVals.add("Uber");
        xVals.add("Paytm");
        xVals.add("Savings");
       // xVals.add("Ola");
        dataSet.setDrawValues(false);
    PieData data = new PieData(xVals, dataSet);
    // In Percentage term
        data.setValueFormatter(new PercentFormatter());
    // Default value
    //data.setValueFormatter(new DefaultValueFormatter(0));
        pieChart.setData(data);
        pieChart.setDescription("Savings");

        pieChart.setDrawHoleEnabled(true);
        pieChart.setTransparentCircleRadius(25f);
        pieChart.setHoleRadius(25f);

        dataSet.setColors(ColorTemplate.VORDIPLOM_COLORS);

        data.setValueTextSize(13f);
        data.setValueTextColor(Color.DKGRAY);
        pieChart.setOnChartValueSelectedListener(this);

        pieChart.animateXY(1400, 1400);


}

    @Override
    public void onValueSelected(Entry e, int dataSetIndex, Highlight h) {

        
        if (e == null)
            return;
        Log.i("VAL SELECTED",
                "Value: " + e.getVal() + ", xIndex: " + e.getXIndex()
                        + ", DataSet index: " + dataSetIndex);

        float datatt = e.getVal();
        Toast.makeText(this, ""+datatt, Toast.LENGTH_SHORT).show();
        datatext.setText(""+datatt);
        //datatitle.setText(""+title);
    }

How can I get the text value of chart and show it on different textviews


Solution

datatext.setText(pieChart.getXAxis().getValues().get(e.getXIndex()));

or

Sting data = ArrayList.get((int) e.getX());


Answered By - Rahul Singh
Answer Checked By - Katrina (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to center the legend in pie chart drawn using MPAndroidChart library?

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

Issue

What I have done: I have created a pie chart using MPAndroidChart library and ended up having the legend in the left corner. I tried changing the pie chart width but then when the items increase legend tends to wrap to a second line.

What I expect: I want the legend to be in the center every time when it updates. Even legend wrap to the second line, I want it to be in the center. I would appreciate any suggestions on this.

Thank you!

enter image description here

<com.github.mikephil.charting.charts.PieChart
        android:id="@+id/chart"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:layout_gravity="center_horizontal"
        >

    </com.github.mikephil.charting.charts.PieChart>

Activity Code :

private void setupPieChart(){

    //pupulating list of PieEntires
    List<PieEntry> pieEntires = new ArrayList<>();
    for( int i = 0 ; i<time.length;i++){
        pieEntires.add(new PieEntry(time[i],activity[i]));
    }
    PieDataSet dataSet = new PieDataSet(pieEntires,"");
    dataSet.setColors(ColorTemplate.MATERIAL_COLORS);
    PieData data = new PieData(dataSet);
    //pie slices text value
    data.setValueTextSize(10);
    //Get the chart
    pieChart.setData(data);
    pieChart.invalidate();
    pieChart.setCenterText("50%");
    pieChart.setDrawEntryLabels(false);
    pieChart.setContentDescription("");
    //pieChart.setDrawMarkers(true);
    //pieChart.setMaxHighlightDistance(34);
    pieChart.setEntryLabelTextSize(12);
    pieChart.setHoleRadius(75);
    //to remove bottom left description
    pieChart.getDescription().setEnabled(false);

    //legend attributes
    Legend legend = pieChart.getLegend();
    legend.setForm(Legend.LegendForm.CIRCLE);
    legend.setTextSize(12);
    legend.setFormSize(20);
    legend.setFormToTextSpace(2);
    //to wrap legend text
    legend.setWordWrapEnabled(true);
    Log.d("legend " ,legend.getEntries().toString());
}

Solution

I was able to center the legend by adding the below line in setupPieChart() mentioned in the question above.

legend.setHorizontalAlignment(Legend.LegendHorizontalAlignment.CENTER);


Answered By - Sachz
Answer Checked By - Mary Flores (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[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)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Friday, April 22, 2022

[FIXED] Why several Pie Charts are being merged into one? MPAndroidChart

 April 22, 2022     android, android-studio, java, mpandroidchart, pie-chart     No comments   

Issue

I want to show 3 several pie charts on the same layout. I insert different data sets to different charts, but by the end all of these data shows on 1 chart and another 2 charts have no data. Could there be a problem that I cannot create several charts on one layout?

private PieChart firstCh, secondCh, thirdCh;
private void openDialog() {

    //code with dialog

        firstCh = dialogStat.findViewById(R.id.firstCharacter);
        secondCh = dialogStat.findViewById(R.id.secondCharacter);
        thirdCh = dialogStat.findViewById(R.id.thirdCharacter);

        ArrayList<PieEntry> statForFirst = new ArrayList<>();
        statForFirst.add(new PieEntry(myNumber, "Kiss"));
        statForFirst.add(new PieEntry(myNumber, "Marry"));
        statForFirst.add(new PieEntry(myNumber, "Kill"));

        ArrayList<PieEntry> statForSecond = new ArrayList<>();
        statForFirst.add(new PieEntry(myNumber, "Kiss"));
        statForFirst.add(new PieEntry(myNumber, "Marry"));
        statForFirst.add(new PieEntry(myNumber, "Kill"));

        ArrayList<PieEntry> statForThird = new ArrayList<>();
        statForFirst.add(new PieEntry(myNumber, "Kiss"));
        statForFirst.add(new PieEntry(myNumber, "Marry"));
        statForFirst.add(new PieEntry(myNumber, "Kill"));

        setNewChart(firstCh, statForFirst);
        setNewChart(secondCh, statForSecond);
        setNewChart(thirdCh, statForThird);

        //code with dialog
    }

private void setNewChart(PieChart chart, ArrayList<PieEntry> entries) {
        chart.getDescription().setEnabled(false);
        chart.getLegend().setEnabled(false);

        PieDataSet dataSet = new PieDataSet(entries, "");
        dataSet.setColors(getResources().getColor(R.color.pinkySarah), getResources().getColor(R.color.lightViola), getResources().getColor(R.color.eyeKiller));

        PieData data = new PieData(dataSet);
        data.setDrawValues(true);
        data.setValueFormatter(new PercentFormatter(chart));
        data.setValueTextSize(10f);
        data.setValueTextColor(R.color.darkViola);

        chart.setData(data);
    chart.invalidate();
    }

This is how it looks in my app For reference, i am using LinearLayout


Solution

Just a typo mistake.

you have added all the data to statForFirst arraylist instead of other two lists. Fix this and you are good to go



Answered By - DrHowdyDoo
Answer Checked By - David Goodson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home
View mobile version

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
All Comments
Atom
All Comments

Copyright © PHPFixing