I'm using MPAndroidChart to create some real time plots of accelerometer data. It seems that memory usage continuously grows the longer you leave the app running so I tried to find a way to remove old data points once they are out of view of the charts scrolling window.
The problem is that once I hit the limit I set for the max number of points to keep/display, points are no longer added but the chart keeps scrolling. The size of my data remains constant (as it should as I'm both adding a new point and removing an old one every update), but no new data gets displayed in the chart anymore.
In my fragment, I'm creating the chart like this in onCreateView
:
accChart = (LineChart) view.findViewById(R.id.accChart);
accChart.setOnChartValueSelectedListener(this);
LineData data = new LineData();
data.setValueTextColor(Color.WHITE);
accChart.setData(data);
Then I listen for accelerometer events using sensor manager, and add an entry every 100ms in onSensorChanged
:
public void onSensorChanged(SensorEvent event) {
sensor = event.sensor;
curAccX = event.values[0];
curAccY = event.values[1];
curAccZ = event.values[2];
long curTime = System.currentTimeMillis();
long diffTime = (curTime - lastUpdate);
// only allow one update every POLL_FREQUENCY.
if(diffTime > POLL_FREQUENCY) {
lastUpdate = curTime;
addEntry(curAccX, curAccY, curAccZ);
}
}
Then to add the entries in addEntry
I'm doing this:
private void addEntry(float curAccX, float curAccY, float curAccZ){
LineData data = accChart.getData();
if (data != null) {
ILineDataSet xData = data.getDataSetByIndex(0);
ILineDataSet yData = data.getDataSetByIndex(1);
ILineDataSet zData = data.getDataSetByIndex(2);
if (xData == null) {
xData = createSetX();
data.addDataSet(xData);
}
if (yData == null) {
yData = createSetY();
data.addDataSet(yData);
}
if (zData == null) {
zData = createSetZ();
data.addDataSet(zData);
}
// add a new x-value first
data.addXValue(String.valueOf(System.currentTimeMillis()));
data.addEntry(new Entry(curAccX, xData.getEntryCount()), 0);
data.addEntry(new Entry(curAccY, yData.getEntryCount()), 1);
data.addEntry(new Entry(curAccZ, zData.getEntryCount()), 2);
//This is where I remove the first entry for each series
if (xData.getEntryCount() > MAX_POINTS_DISPLAYED){
xData.removeFirst();
yData.removeFirst();
zData.removeFirst();
}
// let the chart know it's data has changed
accChart.notifyDataSetChanged();
// limit the number of visible entries
accChart.setVisibleXRangeMaximum(MAX_POINTS_DISPLAYED);
// move to the latest entry
accChart.moveViewToX(data.getXValCount());
}
}
I think the problem lies in my usage of removeFirst
. If I uncomment all those lines, data keeps getting plotted. If I uncomment removeFirst
for only one of the series, that one gets plotted fine, but the other 2 are empty as I described above