I've seen various methods to split a string. I've tryed with both from this post.
I'm trying to read and split the next string: {2b 00 00}
I see that the most common case is to split a message separated by ":", but in this case, my message is separated by spaces.
Trying both ways, with the regular split()
function or with the StringTokenizer
I'm getting a "nullpointerexception" that I supose that is cause because of the space:
private String splitReceivedString(String s) {
String[] separated = s.split(" ");
return separated[1];
}
How could I get the values of this kind of string?
ADDED CODE WITH THE POSSIBLE PROBLEM
After checking some of your answers, I do realize that the problem comes from the bluetooth inputstream. I'm getting null values from it. So, here is the code that I'm using to receive the messages:
The code is almost the same than the bluetoothChat example. But it is modified to adapt to my program, so may I have something wrong.
I've got an MCU wich returns me this String {2b 00 00}
when I send to it another String. I think that this is done in the connectedThread
:
public class ConnectedThread extends Thread {
public void run() {
byte[] buffer = new byte[1024]; // buffer store for the stream
int bytes; // bytes returned from read()
/**Keep listening to the InputStream until an exception occurs*/
while (true) {
try {
/**Read from the InputStream*/
bytes = GlobalVar.mmInStream.read(buffer);
/**Send the obtained bytes to the UI activity*/
GlobalVar.mHandler.obtainMessage(GlobalVar.MESSAGE_READ, bytes, -1, buffer).sendToTarget();
So, this is sending me the string to the handler function in the main activity:
public final Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case GlobalVar.MESSAGE_STATE_CHANGE:
//The code here is irelevant
case GlobalVar.MESSAGE_WRITE:
byte[] writeBuf = (byte[]) msg.obj;
/**construct a string from the buffer*/
String writeMessage = new String(writeBuf);
GlobalVar.mCommunicationArrayAdapter.add(writeMessage);
break;
case GlobalVar.MESSAGE_READ:
byte[] readBuf = (byte[]) msg.obj;
/**construct a string from the valid bytes in the buffer*/
String readMessage = new String(readBuf);
GlobalVar.mCommunicationArrayAdapter.add(readMessage);
GlobalVar.readString = readMessage;
break;
Then, the variable GlobalVar.readString
is the one that I'm getting in the split function:
private String splitReceivedString (String s) {
String[] separated = s.split(" ");
return separated[1];
}
receive1 = splitReceivedString (GlobalVar.readString);
So, the thing is that it isn't reading right the received string, and I don't know how to fix it.