I've been creating a Bluetooth application, everything works fine from turn On and OFF, search device, visible device, open server, set client. Everything works fine and the device could be paired. But when I want to perform data transfer using Input/OutputStream the crash begin.
The code had NO ERROR, but when performing connectedThread function it crashes. here is the code
private class ConnectedThread extends Thread {
private final BluetoothSocket mySocket;
private final InputStream myInStream;
private final OutputStream myOutStream;
public ConnectedThread(BluetoothSocket socket) {
mySocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
}
myInStream = tmpIn; <-------MainActivity.Java:623
myOutStream = tmpOut;
}
public void run() {
byte[] buffer = new byte[1024];
int begin = 0;
int bytes = 0;
while (true) {
try {
bytes += myInStream.read(buffer, bytes, buffer.length - bytes);
for (int i = begin; i < bytes; i++) {
if (buffer[i] == "#".getBytes()[0]) {
myHandler.obtainMessage(1, begin, i, buffer).sendToTarget();
begin = i + 1;
if (i == bytes - 1) {
bytes = 0;
begin = 0;
}
}
}
} catch (IOException e) {
break;
}
}
}
public void write(byte[] bytes) {
try {
myOutStream.write(bytes);
} catch (IOException e) {
}
}
public void cancel() {
try {
mySocket.close();
} catch (IOException e) {
}
}
Handler myHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
byte[] writeBuf = (byte[]) msg.obj;
int begin = (int) msg.arg1;
int end = (int) msg.arg2;
switch (msg.what) {
case 1:
String writeMessage = new String(writeBuf);
writeMessage = writeMessage.substring(begin, end);
break;
}
}
};
}
The connectedThread is trigered from here
transferBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ConnectedThread t = new ConnectedThread(socket);<------MainActivity.Java:192
t.start();
});
The Logcat show this
07-14 02:53:04.937 16812-16812/com.example.heszrave.bluetoothremote E/AndroidRuntime﹕ FATAL EXCEPTION: main java.lang.NullPointerException at com.example.heszrave.bluetoothremote.MainActivity$ConnectedThread.(MainActivity.java:623) at com.example.heszrave.bluetoothremote.MainActivity$6.onClick(MainActivity.java:192)
When I click on MainActivity.Java:623, it pointed to myInStream = tmpIn;
for MainActivity.Java:192 it pointed to the firing event ConnectedThread t = new ConnectedThread(socket);