0

Hallo I have a problem with my code. I want to check the app if it's enabled or not. If bluetooth is enabled and a device is paired I want to connect to the device, if not I want to try to connect to it.

If my bluetooth device is on and I'm connected all works great and I'm getting the data, but if the device is off or not paired I'm getting this:

java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.bluetooth.BluetoothAdapter.isEnabled()' on a null object reference.

hope you can help me.

Main Activity Fragment:

public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        final View view = inflater.inflate(R.layout.fragment_wind, container, false);

........

   try
                {
                    findBT();
                    openBT();
                }
                catch (IOException ex) { }


        //Send Button


        //Close button
        closeButton.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View v)
            {
                try
                {
                    closeBT();
                }
                catch (IOException ex) { }
            }
        });
.........


void findBT()
    {
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if(mBluetoothAdapter == null) {
            arduinodata.setText("Bluetooth Device not Found");
        }
        if (!mBluetoothAdapter.isEnabled()) {
            Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableBluetooth, 0);

        }



        Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
        if(pairedDevices.size() > 0)
        {
            for(BluetoothDevice device : pairedDevices)
            {
                if(device.getName().equals("HC05"))
                {
                    mmDevice = device;
                    break;
                }
            }
        }
        arduinodata.setText("Bluetooth Device Found");
    }

    void openBT() throws IOException
    {
        UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); //Standard SerialPortService ID
        mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);
        mmSocket.connect();
        mmOutputStream = mmSocket.getOutputStream();
        mmInputStream = mmSocket.getInputStream();

        beginListenForData();

        arduinodata.setText("Bluetooth Opened");
    }

    void beginListenForData()
    {
        final Handler handler = new Handler();
        final byte delimiter = 10; //This is the ASCII code for a newline character

        stopWorker = false;
        readBufferPosition = 0;
        readBuffer = new byte[1024];
        workerThread = new Thread(new Runnable()
        {
            public void run()
            {
                while(!Thread.currentThread().isInterrupted() && !stopWorker)
                {
                    try
                    {
                        int bytesAvailable = mmInputStream.available();
                        if(bytesAvailable > 0)
                        {
                            byte[] packetBytes = new byte[bytesAvailable];
                            mmInputStream.read(packetBytes);
                            for(int i=0;i<bytesAvailable;i++)
                            {
                                byte b = packetBytes[i];
                                if(b == delimiter)
                                {
                                    byte[] encodedBytes = new byte[readBufferPosition];
                                    System.arraycopy(readBuffer, 0, encodedBytes, 0, encodedBytes.length);
                                    final String data = new String(encodedBytes, "US-ASCII");
                                    readBufferPosition = 0;

                                    handler.post(new Runnable()
                                    {
                                        public void run()
                                        {
                                            arduinodata.setText(data);
                                        }
                                    });
                                }
                                else
                                {
                                    readBuffer[readBufferPosition++] = b;
                                }
                            }
                        }
                    }
                    catch (IOException ex)
                    {
                        stopWorker = true;
                    }
                }
            }
        });

        workerThread.start();
    }


    void closeBT() throws IOException
    {
        stopWorker = true;
        mmOutputStream.close();
        mmInputStream.close();
        mmSocket.close();
        arduinodata.setText("Bluetooth Closed");
    }
paradx
  • 74
  • 12
Julian
  • 1
  • 3
  • Yes the problem is that i dont know how to solve it... i have read your link but it does not describe my problem... the NPE is in line if (!mBluetoothAdapter.isEnabled()) { – Julian May 29 '19 at 09:16
  • `mBluetoothAdapter` is null, and you should use an `else if` instead of two separate `if` statements. As right now, you first check if it is null and then - while it is possibly null - go ahead and call a method on it. – Mark Rotteveel May 29 '19 at 18:42

1 Answers1

-1

isEnabled() method of bluetooth adapter might be a Wrapper Boolean class which can have null value. If we check for true or false directly inside if condition, there is a possibility of null pointer exception as shown below:

Below code throws null pointer exception:

    Boolean val = null;

    if (val) {
        System.out.println("Will not work incase of null");
    }

Below code works:

    if (null != val && val) {
        System.out.println("Works");
    }