I currently have a bluetooth service wherein there is a thread that manages the bluetooth connection after it has been established. When i check if the thread is alive with isAlive, then i get true if i remain in the same activity that establishes the connection. But, if i call the same function from a different activity to check if it is alive, then i get the following error:
java.lang.NullPointerException: Attempt to invoke virtual method ‘boolean com.example.bluetooth.BTservice$ConnectedThread.isAlive()’ on a null object reference
this is the thread in question:
public class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
Log.d(TAG, "ConnectedThread: Starting.");
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
//dismiss the progressdialog when connection is established
try{
mProgressDialog.dismiss();
}catch (NullPointerException e){
System.out.println("Null pointer exception");
e.printStackTrace();
}
try {
tmpIn = mmSocket.getInputStream();
tmpOut = mmSocket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
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) {
// Read from the InputStream
try {
bytes = mmInStream.read(buffer);
String incomingMessage = new String(buffer, 0, bytes);
Log.d(TAG, "InputStream: " + incomingMessage);
Intent incomingMessageIntent = new Intent("incomingMessage");
incomingMessageIntent.putExtra("incomingMessage", incomingMessage);
} catch (IOException e) {
Log.e(TAG, "write: Error reading Input Stream. " + e.getMessage() );
break;
}
}
}
//Call this from the main activity to send data to the remote device
public void write(byte[] bytes) {
String text = new String(bytes, Charset.defaultCharset());
Log.d(TAG, "write: Writing to outputstream: " + text);
try {
mmOutStream.write(bytes);
} catch (IOException e) {
Log.e(TAG, "write: Error writing to output stream. " + e.getMessage() );
}
}
/* Call this from the main activity to shutdown the connection */
public void cancel() {
try {
mmSocket.close();
System.out.println("Closing socket");
} catch (IOException e) { }
}
}
The function that i am calling is also in the service class
public void checkAliveStatus(){ System.out.println("is connected thread alive"+mConnectedThread.isAlive()); }
I have tried to create another activity to see if the issue was that i returned to the main activity but the same error occurs.
user24815990 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.