java - 将多个字符串组合成一个
问题描述
我在一个蓝牙应用程序上工作,我在几个字符串包中接收我的数据。(我使用速度波特率 9600)
例子:
02-19 09:44:59.516 12659-12659/com.example.appcopeeks I/RECEIVER: [1/1/0
02-19 09:44:59.516 12659-12659/com.example.appcopeeks I/RECEIVER: 0:12:32]
02-19 09:44:59.526 12659-12659/com.example.appcopeeks I/RECEIVER: Timesta
02-19 09:44:59.536 12659-12659/com.example.appcopeeks I/RECEIVER: mp=94668
02-19 09:44:59.546 12659-12659/com.example.appcopeeks I/RECEIVER: 5552 ID=
02-19 09:44:59.556 12659-12659/com.example.appcopeeks I/RECEIVER: 40 Value
02-19 09:44:59.566 12659-12659/com.example.appcopeeks I/RECEIVER: =2453
这是我得到的视频screenpresso.com/=8kakb 我想把所有这些放在一个字符串中。
例子:
[11/2/19 9:48:25] Timestamp=1549878505 ID=4 Value=2475
我试过了,但没有用。
public class CapteurActivity extends AppCompatActivity {
private StringBuilder dataFull = new StringBuilder();
...
public void onReceive(Context context, Intent intent){
switch (intent.getAction()){
//writes the data received in the EditText
case BGXpressService.BGX_DATA_RECEIVED: {
String stringReceived = intent.getStringExtra("data");
if ( stringReceived != null ) {
if ( stringReceived.startsWith("[")) {
getAssembleData(intent);
}
}
Log.d("Test DataFull: ",dataFull.toString());
...
}
}
}
...
public String getAssembleData(Intent intent){
StringBuilder dataFull = new StringBuilder();
String stringReceived = intent.getStringExtra("data");
while (!stringReceived.contains("[")){
dataFull.append(stringReceived);
}
return dataFull.toString();
}
}
感谢您花时间阅读。
解决方案
你调用了两次 toAssemble 并且你没有检查空指针异常。这是一种更简单的方法,可以满足您的需求。lastStringReceived 将存储最后一个 String 程序集,直到收到新的 String。
public class CapteurActivity extends AppCompatActivity {
static String lastStringReceived = "";
StringBuffer buffer = new StringBuffer();
...
public void onReceive(Context context, Intent intent){
switch (intent.getAction()){
//writes the data received in the EditText
case BGXpressService.BGX_DATA_RECEIVED: {
String stringReceived = intent.getStringExtra("data");
if ( stringReceived != null ) {
if ( stringReceived.startsWith("[")) {
lastStringReceived = buffer.toString();
buffer = new StringBuffer();
}
buffer.append(stringReceived)
}
...
}
}
}
推荐阅读
- drools - 制定规则以检查子数据
- reactjs - React Js (web) 的运行时 DEV 环境变量
- php - PHP foreach 通过一个键->值循环遍历多维数组输出组
- r - Rmarkdown 运行,但在发布时产生连接错误
- php - php脚本仅将第一张图片上传到数据库
- postgresql - PostGreSQL 函数 - 整数的输入语法无效
- scala - 使用折叠连接所有数据框列,使用 Spark / Scala 减少
- java - Firebase 实时数据库中的节点是什么?
- swagger - 大摇大摆的多态性没有按预期工作
- sql - 检查长度约束在 Oracle11g sqlplus 中不起作用