首页 > 解决方案 > 将多个字符串组合成一个

问题描述

我在一个蓝牙应用程序上工作,我在几个字符串包中接收我的数据。(我使用速度波特率 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();
 }
}

感谢您花时间阅读。

标签: javastringbluetooth

解决方案


你调用了两次 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)
                    }

        ...
  }
 }
}


推荐阅读