0

我在 android studio 中制作了一个屏幕,用于管理蓝牙的某些方面,例如搜索设备、打开和关闭等。当我运行应用程序时出现了问题,将蓝牙图像从打开更改为关闭时出现 NullPointer 错误,反之亦然。

到目前为止我的代码(简化):

private ListView listView;
private ArrayList<String> mDeviceList = new ArrayList<>();
Button mBotOn, mBotOff,mBotDescubrir, mBotEmparejar, mBotEmp;
private BluetoothAdapter mBlueAdapter;

 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.ajustes_conexion_sensores);

    listView = findViewById(R.id.listView);

    mBlueAdapter = BluetoothAdapter.getDefaultAdapter();


    final IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
    if (mBlueAdapter == null) {
        mEstadoBlueTv.setText("Bluetooth no disponible.");
    } else {
        mEstadoBlueTv.setText("Bluetooth está disponible.");
    }

    mBotDescubrir.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            registerReceiver(mReceiver, filter);
            mBlueAdapter.startDiscovery();
        }
    });
}
    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if(BluetoothDevice.ACTION_FOUND.equals(action)){
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                mDeviceList.add(device.getName() + "\n" + device.getAddress());
                listView.setAdapter(new ArrayAdapter<String>(context, 
                android.R.layout.simple_list_item_1, mDeviceList));
            }
        }
    };

我在这里得到 NullPointer 异常:

if (mBlueAdapter.isEnabled()) {
        mBluetIv.setImageResource(R.drawable.bt_on);
    } else {
        mBluetIv.setImageResource(R.drawable.bt_off);
    }

错误:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean 
android.bluetooth.BluetoothAdapter.isEnabled()' on a null object reference
at serenaApp.serenaapp.AjustesConexionSensores.onCreate(AjustesConexionSensores.java:62)

提前谢谢你

4

1 回答 1

1
if(mBlueAdapter!=null && mBlueAdapter.isEnabled() !=null && mBluetIv!=null){

if (mBlueAdapter.isEnabled()) {
  mBluetIv.setImageResource(R.drawable.bt_on);
} else {
  mBluetIv.setImageResource(R.drawable.bt_off);
}

}
于 2020-02-11T10:19:52.077 回答