I am trying to read a file where each line has X and Y readings. For each line I therefore want to plot the coordinates. I have a button that when clicked, should change to a "pause" button and when the file is read and the graph fully plotted it must change back to a "play" button. For each coordinate I use the stepPlotter function I created, after each X-Y coordinate plot I want to delay the next plotting.
For some reason the graph is plotted only after the whole file is read, and the image button changes from "PLAY" to "PAUSE" only when the file is read too. In fact what happens is that the "play" button stays as "play". Since it changes internally to "pause" (but is not visually changed) and then back to "play" when the file finishes reading. So no visual change.
My code looks as follows:
In my onCreate() I have the following:
//play/pause button
fabButton = findViewById(R.id.fab);
mLinearLayout = findViewById(R.id.linearLayoutGraph);
//setting up graph with origin
scatterPlot = new ScatterPlot("Position");
scatterPlot.addPoint(0, 0);
mLinearLayout.addView(scatterPlot.getGraphView(getApplicationContext()));
fabButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!isTracking) {
isTracking = true;
fabButton.setImageDrawable(ContextCompat.getDrawable(TrackingActivity.this, R.drawable.ic_pause_black_24dp));
readFile(fileToRead);
} else {
isTracking = false;
fabButton.setImageDrawable(ContextCompat.getDrawable(TrackingActivity.this, R.drawable.ic_play_arrow_black_24dp));
}
}
});
The reading file function is as follows:
private void readFile(File file){
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
//SKIPPING first three lines (these are not coordinate data)
br.readLine();
br.readLine();
br.readLine();
while ((line = br.readLine()) != null) {
String[] readings = line.split(";");
stepPlotter(readings);
Thread.sleep(50);
}
br.close();
isTracking =false;
} catch (InterruptedException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Finally, the plotting function is:
private void stepPlotter(String[] readings){
float rPointX = -Float.parseFloat(readings[8]);
float rPointY = Float.parseFloat(readings[9]);
scatterPlot.addPoint(rPointX, rPointY);
mLinearLayout.removeAllViews();
mLinearLayout.addView(scatterPlot.getGraphView(getApplicationContext()));
}
EDIT: I use achartengine for plotting
I managed to make it work by using Thread as follows: