2013-03-14 76 views
0

我試圖使用Android的樣本BlueToothChat每次但有件事我不明白:的getBytes的toString不會產生相同的結果

byte[] send = message.getBytes(); 
Log.d("SEND_BYTE", send.toString()); 
mChatService.write(send); 

這裏,消息是一個字符串,然後轉換爲字節,我想爲了被髮送。但是當我檢查日誌時,即使我輸入的消息很長,send.toString()部分也非常短。更糟糕的是,如果我輸入兩次相同的信息,我會得到2個不同的日誌,我發現這很奇怪。 下面是我得到的日誌中的消息hello,連續三次:

[[email protected] 
[[email protected] 
[[email protected] 

一定有什麼東西(也許很簡單的),我沒有得到,但可以(T弄清楚什麼是你能不能幫我這個

編輯:? 也許是有用的添加代碼的下面,所以在這裏是完整的代碼:

byte[] send = message.getBytes(); 
Log.d("SEND_BYTE", send.toString()); 
mChatService.write(send); 

// Reset out string buffer to zero and clear the edit text field (buffer is used in the write function) 
mOutStringBuffer.setLength(0); 
mOutEditText.setText(mOutStringBuffer); 
+1

默認的toString方法返回的getClass()的getName()+ '@' + Integer.toHexString(hashCode()方法) – 2013-03-14 10:55:09

回答

6

是的,在字節數組上調用toString()是個壞主意。數組不會覆蓋toString(),因此您將獲得默認行爲Object.toString()

要扭轉String.getBytes()電話,你想:

Log.d("SEND_BYTE", new String(send)); 

還是看字節更直接:

Log.d("SEND_BYTE", Arrays.toString(send)); 

然而,我會強烈建議您做直。相反,您應該在轉換爲二進制文件或從二進制文件轉換時指定編碼,否則將使用平臺默認編碼。聊天服務期待什麼編碼?例如,如果該公司預計,UTF-8:

byte[] send = message.getBytes("UTF-8"); 
Log.d("SEND_BYTE", Arrays.toString(send)); 
mChatService.write(send); 
+0

非常感謝,您的解決方案完美無缺 – WhiskThimble 2013-03-14 11:10:04

1

您需要創建一個新的字符串對象得到實際的字符串

String senddata=new String(send); 
1

嘗試:

Log.d("SEND_BYTE", new String(send, "UTF-8");); 
相關問題