我需要从数组中添加数据,然后实时添加数据。我可以分别做两件事,但是当我想要一起做所有事情时,应用程序会在它开始之前关闭。
这个想法是显示我通过蓝牙接收的数据,当我收到5系列时,我们的想法是能够随时可视化5。我想要做的是绘制已经到达我的数据并添加我收到的数据,然后我可以通过重置图表并加载另一个系列的值来查看不同的系列。
我附上了代码。
非常感谢。
public class MainActivity extends AppCompatActivity {
private static final Random RANDOM = new Random();
private LineGraphSeries<DataPoint> series;
private int lastX = 0;
double[] x= new double[10];
double[] y= new double[10];
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// we get graph view instance
values();
LineGraphSeries<DataPoint> series;
GraphView graph = (GraphView) findViewById(R.id.graph);
// data
series = new LineGraphSeries<>(data());
graph.addSeries(series);
// customize a little bit viewport
Viewport viewport = graph.getViewport();
viewport.setYAxisBoundsManual(true);
viewport.setXAxisBoundsManual(true);
viewport.setMinY(0);
viewport.setMaxY(10);
viewport.setMinX(0);
viewport.setMaxX(30);
series.setThickness(1);
}
@Override
protected void onResume() {
super.onResume();
// we're going to simulate real time with thread that append data to the graph
new Thread(new Runnable() {
@Override
public void run() {
// we add 100 new entries
for (int i = 0; i < 10; i++) {
runOnUiThread(new Runnable() {
@Override
public void run() {
addEntry();
}
});
// sleep to slow down the add of entries
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// manage error ...
}
}
}
}).start();
}
// add random data to graph
private void addEntry() {
// here, we choose to display max 10 points on the viewport and we scroll to end
series.appendData(new DataPoint(lastX++, RANDOM.nextDouble() * 10d), false, 1800);
}
public DataPoint[] data(){
DataPoint[] values = new DataPoint[10]; //creating an object of type DataPoint[] of size 'n'
for(int i=0;i<10;i++){
DataPoint v = new DataPoint(x[i],y[i]);
values[i] = v;
}
return values;
}
private void values(){
for(int i=0;i<10;i++) {
x[i]=i;
y[i]=i;
}
}
}