将多个String组装成一个

时间:2019-02-19 08:54:00

标签: java string bluetooth

我正在使用蓝牙应用程序,并且我通过数个String程序包接收数据。 (我使用的是Baud 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();
 }
}

感谢您抽出宝贵的时间阅读。

1 个答案:

答案 0 :(得分:1)

您两次调用toAssemble,并且没有检查Null Pointer Exception。这是一种更简单的方法,可以满足您的需求。 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)
                    }

        ...
  }
 }
}