lakshman
lakshman

Reputation: 191

How to convert String to Bar entry for MPCharts in android

In my android application, I am new to graphs and using MPchart library to draw the graphs. I'm displaying the graph using string array on both - X axis and Y axis.

For x axis I created it successfully but for Y axis I need to convert my ArrayList<String> to BarData array list. I don't know how to do convert it. Can anyone tell me how to achieve this?

For X axis:

private ArrayList<String> getXAxis() {
            ArrayList<String> xAxis = new ArrayList<>();
            xAxis = new ArrayList<String>(Arrays.asList(bar_graph_names)); //converting string to arraylist
            return xAxis;
        }

For Y axis plotting values:

private ArrayList<BarDataSet> getData() {
        ArrayList<String> yAxis_conv = new ArrayList<>();
        yAxis_conv = new ArrayList<String>(Arrays.asList(bar_graph_values));

        ArrayList<BarDataSet> yAxis_Datasets=null;
        ArrayList<BarEntry> yAxis = new ArrayList<>();

        for(int i = 0; i < bar_graph_values.length; i++)
        {
            BarEntry [] barentry = new BarEntry[bar_graph_values.length];
            barentry[i] = new BarEntry(Float.valueOf(yAxis_conv.get(i)),i);
        }           

        BarDataSet barDataSet1 = new BarDataSet(yAxis_conv , "");//Error occurring line
        barDataSet1.setColors(ColorTemplate.COLORFUL_COLORS);
        yAxis_Datasets = new ArrayList<>();
        yAxis_Datasets.add(barDataSet1);
        return yAxis_Datasets;
    }

Upvotes: 1

Views: 5365

Answers (1)

InTwoMinds
InTwoMinds

Reputation: 675

BarData object (which you give to the chart View) consist of one List representing x-values and one or more BarDataSet objects representing y-values data. BarDataSet object has String name and List of y-values.

Your structure of this objects is simply wrong. (for starters yAxis_conv is List<String>, where BarDataSet requires List<BarEntry>). There's more mistakes, but i'm not gonna point them out, just have some working code below:

private void setData() {
    ArrayList<String> xVals = new ArrayList<String>();
    ArrayList<BarEntry> yVals = new ArrayList<BarEntry>();

    xVals = new ArrayList<String>(Arrays.asList(bar_graph_names));
    for(int i=0; i < bar_graph_values.length; i++) {
        BarEntry entry = new BarEntry(Float.valueOf(bar_graph_values[i]), i);
        yVals.add(entry);
    }
    BarDataSet newSet = new BarDataSet(yVals, "DataSet");
    BarData data = new BarData(xVals, newSet);
    mChart.setData(data);
}

Upvotes: 5

Related Questions