我目前正试图绘制我通过与微控制器板的蓝牙通信接收的数据。每次数据传输(每200毫秒)发送一个字符串的4个字符(4个数字)到我的android设备,在那里我能够显示一个textView的值,每次有一些新的数据可用时更新。这将在MainActivity中持续10秒。
要得到一个数组,我想绘制的数据,我保存每个字符串在字符串列表中,像这样:
// Create Array List to send to xyPlot activity
List<String> incomingStringData = new ArrayList<>();
// more code happening...
String loadCellString = recDataString.substring(1, 5); // get sensor value from string between indices 1-5
incomingStringData.add(loadCellString); // Adding each incoming substring to List<String> incomingStringData
// more code happening
// On button click send data to xyPlot activity
btnPlot.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent xyPlotScreen = new Intent(getApplicationContext(), xyPLot.class);
//Sending data to another Activity
String[] xyPlotStringArray = incomingStringData.toArray(new String[0]);
xyPlotScreen.putExtra("string-array", xyPlotStringArray);
// Start plotscreen (xyPlot) activity
startActivity(xyPlotScreen);
}
}
这个数据列表发送到活动xyPlot(我从androidplot的简单xyPlot示例复制,感谢btw),它是这样处理的:
// Get String Array from Motor Control (MainActivity):
Intent xyPlotScreen = getIntent();
String[] thrustStringArray = xyPlotScreen.getStringArrayExtra("string-array");
// Convert String-Array into an Integer to be able to plot:
String[] parts = thrustStringArray[0].split(",");
Integer[] intThrust = new Integer[parts.length];
for(int n = 0; n < parts.length; n++) {
intThrust[n] = Integer.parseInt(parts[n]);
}
// Create the Number series for plotting
Number[] thrustSeries = intThrust;
// Turn the above arrays into XYSeries':
// (Y_VALS_ONLY means use the element index as the x value
XYSeries thrustSeries = new SimpleXYSeries(Arrays.asList(thrustArray),
SimpleXYSeries.ArrayFormat.XY_VALS_INTERLEAVED,"Thrust");
现在我使用XY_VALS_INTERLEAVED
只是为了知道我是否可以绘制我正在获得的传入数据,即使它没有意义(稍后我的字符串将由x轴的时间戳组成)。
数据类型"Number"(也是Integer,对吧??)当然不支持String数组。我做了一个从String到integer的转换然后我就可以构建应用了
当我开始情节活动时,我得到这个错误消息:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.controlcenter.controlcenter/com.controlcenter.controlcenter.xyPLot}: java.lang.IndexOutOfBoundsException: Cannot auto-generate series from odd-sized xy List.
即使当我改变我的android设备上输入数据的频率(每秒1个值,所以10个值),我得到相同的错误信息。我想这个问题是在我把字符串转换成整数的地方。但是我无法找到一种正确的方法来进行这种转换,以便从Number[]
类型的数据中绘制传感器数据。
希望你们能帮助我。
提前感谢!克里斯。
你看到的错误只是说你传递给Androidplot的数据数组有奇数个元素,这是非法的,当使用交错模式:交错意味着你是传递对x/y值顺序。如果该数组的大小为奇数,则表示缺少x或y分量。
你可以用几种方法来解决这个问题。要使程序正常工作,最简单的方法可能是修改for循环,使其忽略读取到的奇数的最终值:
int partsLen = parts.length;
if(partsLen < 2) {
// do something to gracefully avoid continuing as theres not enough data to plot.
} else {
if(partsLen % 2 == 1) {
// if the size of the input is odd, ignore the last element to make it even:
partsLen--;
}
}
for(int n = 0; n < partsLen; n++) {
intThrust[n] = Integer.parseInt(parts[n]);
}