When the function send is called i get the followwing error:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.OutputStream android.bluetooth.BluetoothSocket.getOutputStream()' on a null object reference
Why does it work in my Oncreate but not in send?
public class MainActivity extends AppCompatActivity {
private Button sende;
public BluetoothSocket bluetoothSocket;
BluetoothAdapter bluetoothAdapter;
static final UUID mUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
Bluetooth_an();
sende = findViewById(R.id.button);
BluetoothDevice blue = bluetoothAdapter.getRemoteDevice("00:19:08:36:1B:BA");
System.out.println(blue.getName());
System.out.println(blue.getUuids().toString());
BluetoothSocket bluetoothSocket = null;
int counter = 0;
do {
try {
bluetoothSocket = blue.createRfcommSocketToServiceRecord(mUUID);
System.out.println(bluetoothSocket);
bluetoothSocket.connect();
System.out.println(bluetoothSocket.isConnected());
} catch (IOException e) {
e.printStackTrace();
}
counter++;
} while (!bluetoothSocket.isConnected() && counter < 20);
sende.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
send();
}
});
try {
OutputStream outputStream = bluetoothSocket.getOutputStream();
outputStream.write(1);
} catch (IOException e) {
e.printStackTrace();
}
Until here it is working
}
private void Bluetooth_an() {
...
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
...
}}}
private void send(){
try {
OutputStream outputStream = bluetoothSocket.getOutputStream();
outputStream.write(1);
} catch (IOException e) {
e.printStackTrace();
}}}
Calling this send gives me an error