0

In BluetoothChat source code i cannot understand some part of the code-

 private void sendMessage(String message) {

// Check that we're actually connected before trying anything
    if (mChatService.getState() != BluetoothChatService.STATE_CONNECTED) {
        Toast.makeText(this, R.string.not_connected, Toast.LENGTH_SHORT).show();
        return;
    }

// Check that there's actually something to send
if (message.length() > 0) {
    // Get the message bytes and tell the BluetoothChatService to write
    byte[] send = message.getBytes();
    mChatService.write(send);

    // Reset out string buffer to zero and clear the edit text field
    mOutStringBuffer.setLength(0);
    mOutEditText.setText(mOutStringBuffer);
}

}

Here, I undersatnd that byte[] send is a array but cannot understand why i am intializing this array = message.getBytes();

May be its a very silly question but as i am a beginner so i think i should clear this part. Java experts need your suggestion.

user3732316
  • 63
  • 1
  • 7
  • 1
    If you mean that those lines could merge, you are right: `mChatService.write(message.getBytes());` is valid code. It might be done for readability. – M. Mimpen Jun 25 '14 at 09:50

2 Answers2

0

The 'send' has to be a byte array as the mChatService.write() method accepts byte array. you may read a bit more on the following question: Java Byte Array to String to Byte Array

Community
  • 1
  • 1
Hongzheng
  • 385
  • 4
  • 10
0

The chat service sends binary data, the bytes.

In java text (String, char, Reader/Writer) is a black box of Unicode text, so one may combine all kinds of scripts and languages.

To get the bytes for a specific encoding one does:

String s = "...";
byte[] b = s.getBytes(s, encoding);

Those bytes are in that given encoding.

and reversed:

s = new String(b, encoding);

The version of String.getBytes() without encoding can cause an error: it uses the default, platform encoding, which differs per computer.

Best would have been to return bytes in a Unicode format, like UTF-8.

byte[] b = s.getBytes(StandardCharsets.UTF_8);
Joop Eggen
  • 107,315
  • 7
  • 83
  • 138