如何解决我的Android应用中的NullPointer错误?

 收藏

我已经在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)

提前谢谢你

回复