有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

BluetoothAdapter上的安卓 Java NullPointerException。isEnabled()

你好,我的代码有问题。 我想检查应用程序是否已启用。 如果蓝牙已启用且设备已配对,则我希望连接到该设备,否则我希望尝试连接到该设备

如果我的蓝牙设备已打开且已连接,则所有功能都很好,并且我正在获取数据,但如果设备已关闭或未配对,则我将获取以下信息:

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

希望你能帮助我

主要活动片段:

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");
    }

共 (1) 个答案

  1. # 1 楼答案

    bluetooth adapter的isEnabled()方法可能是一个包装布尔类,它可以有空值。如果我们直接在If条件中检查true或false,则可能出现空指针异常,如下所示:

    下面的代码引发空指针异常:

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

    以下代码有效:

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