Android: Take data from CSV file and plot line chart using MPAndroidChart

Published

In my application, I’m using MPAndroidchart, where I’ve to take data from CSV file and plot it. Also, when CSV file is updated by adding more data the chart should take automatically updated data as well and plot it.

My CSV looks like as follows:

2020/11/11, 01:07AM, 92.6°F

2020/11/15, 02:51PM, 96.9°F

2020/11/15, 02:52PM, 93.6°F

List of Problems:

  1. In above data, Although Date/Time is there, I’m taking only last column data (Temperature data) and plotting it versus Date/Time (within MPAndroidchart X-Axis formatter). But in my case, the chart is empty and X-Axis is not showing.
  2. Next, if I want to take both Date/Time (String datatype) and Temperature data directly from CSV file and plot it how X-Axis should be formatted, Add Series, Set data on chart and plotted it using MPAndroidchart?

Here’s my code:

public class ChartActivity extends BaseAppCompatActivity {

    private Toolbar toolbar;
    private File logFile;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chart);

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);


        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setDisplayShowHomeEnabled(true);
            toolbar.setNavigationOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    finish();
                }
            });
        }
}
       

  public void onResume() {
        super.onResume();


        logFile = (File) getIntent().getExtras().get(Constants.EXTRA_LOG_FILE);
        if (logFile != null) {
            toolbar.setTitle(logFile.getName() + getString(R.string.charting));

              try {
                setLogText(logFile);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }



        }
    }

  

    public float Parsefloat(String strNumber) {
        if (strNumber != null && strNumber.length() > 0) {
            try {
                return Float.parseFloat(strNumber);
            } catch(Exception e) {
                return -1;   // or some value to mark this field is wrong. or make a function validates field first ...
            }
        }
        else return 0;
    }

    private void setLogText(File file) throws FileNotFoundException {

      LineChart chart = findViewById(R.id.chart1);

        // no description text
        chart.getDescription().setEnabled(false);

        // enable touch gestures
        chart.setTouchEnabled(true);

        chart.setDragDecelerationFrictionCoef(0.9f);

        // enable scaling and dragging
        chart.setDragEnabled(true);
        chart.setScaleEnabled(true);
        chart.setDrawGridBackground(false);
        chart.setHighlightPerDragEnabled(true);

        // set an alternative background color
        chart.setBackgroundColor(Color.WHITE);
        chart.setViewPortOffsets(0f, 0f, 0f, 0f);


         // get the legend (only possible after setting data)
        Legend l = chart.getLegend();
        l.setEnabled(false);

        XAxis xAxis = chart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.TOP_INSIDE);
        xAxis.setTypeface(tfLight);
        xAxis.setTextSize(10f);
        xAxis.setTextColor(Color.WHITE);
        xAxis.setDrawAxisLine(false);
        xAxis.setDrawGridLines(true);
        xAxis.setTextColor(Color.rgb(255, 192, 56));
        xAxis.setCenterAxisLabels(true);
        xAxis.setGranularity(0.5f); // one hour
        xAxis.setValueFormatter(new ValueFormatter() {

            private final SimpleDateFormat mFormat = new SimpleDateFormat("dd MMM HH:mm a", Locale.ENGLISH);

            @Override
            public String getFormattedValue(float value) {

                long millis = TimeUnit.MINUTES.toMillis((long) value);
                return mFormat.format(new Date(millis));
            }
        });

        YAxis leftAxis = chart.getAxisLeft();
        leftAxis.setPosition(YAxis.YAxisLabelPosition.INSIDE_CHART);
        leftAxis.setTypeface(tfLight);
        leftAxis.setTextColor(ColorTemplate.getHoloBlue());
        leftAxis.setDrawGridLines(true);
        leftAxis.setGranularityEnabled(true);
        leftAxis.setAxisMinimum(0f);
        leftAxis.setAxisMaximum(170f);
        leftAxis.setYOffset(-9f);
        leftAxis.setTextColor(Color.rgb(255, 192, 56));

        YAxis rightAxis = chart.getAxisRight();
        rightAxis.setEnabled(false);

        ArrayList<Entry> values = new ArrayList<>();



        Scanner inputStream;

        inputStream = new Scanner(file);

        while(inputStream.hasNext()){
            String line= inputStream.next();

            if (line.equals("")) { continue; } // <--- notice this line

            String[] values = line.split(",");
            String V = values[0];  // Date
            String W= values[1];   // Time (12 hours format)
            String X= values[2];   // Temperature

            String display = X;

            if(!TextUtils.isEmpty(display)) {
                display  = display.substring(0, display.length()-2);

                X = display;
            }

            float T = Parsefloat(X); // converts string temperature to float value


              long now = TimeUnit.MILLISECONDS.toMinutes(System.currentTimeMillis());
              double to = now;
              values.add(new Entry((float) to, T));

         }

        inputStream.close();


         // create a dataset and give it a type
        LineDataSet set1 = new LineDataSet(values, "DataSet 1");
        set1.setAxisDependency(AxisDependency.LEFT);
        set1.setColor(ColorTemplate.getHoloBlue());
        set1.setValueTextColor(ColorTemplate.getHoloBlue());
        set1.setLineWidth(1.5f);
        set1.setDrawCircles(false);
        set1.setDrawValues(false);
        set1.setFillAlpha(65);
        set1.setFillColor(ColorTemplate.getHoloBlue());
        set1.setHighLightColor(Color.rgb(244, 117, 117));
        set1.setDrawCircleHole(false);

        // create a data object with the data sets
        LineData data = new LineData(set1);
        data.setValueTextColor(Color.WHITE);
        data.setValueTextSize(9f);

        // set data
        chart.setData(data);
       

    }
}

I need a chart similar to like this as below:

Chart Sample Figure

Please help me out. Thank you!

Source: Android Questions

Published
Categorized as android, java, mpandroidchart

Answers

Suppose we have data in this format,
Here what happens that the MP Bar chart does not aggregate the year wise data, if I am keeping YEAR as X and RICE(KG) as Y – (I do not want to show AREA in any way.)
Instead, it shows stacked bar based on Area….

CSV Format-
AREA, YEAR, RICE(KG)
North, 2014, 50
North, 2015, 55
North, 2016, 54
South, 2014, 52
South, 2015, 53
South, 2016, 50
West, 2014, 51
West, 2015, 49
West, 2016, 48
East, 2014, 55
East, 2015, 52
East, 2016, 49


Manoj

Leave a Reply

Still Have Questions?


Our dedicated development team is here for you!

We can help you find answers to your question for as low as 5$.

Contact Us
faq