简体   繁体   English

如何在我的 Android 应用程序中解决此 NullPointer 错误?

[英]How can I solve this NullPointer error in my Android app?

I've made a screen in android studio that manages some aspects of bluetooth like searching for devices, on and off and so on.我在 android studio 中制作了一个屏幕,用于管理蓝牙的某些方面,例如搜索设备、打开和关闭等。 The problem appeared when I ran the app, I get a NullPointer error when changing the bluetooth images from on to off and viceversa.当我运行应用程序时出现问题,将蓝牙图像从打开更改为关闭时出现 NullPointer 错误,反之亦然。

My code so far (simplified):到目前为止我的代码(简化):

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

I get the NullPointer Exception here:我在这里得到 NullPointer 异常:

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

The error:错误:

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)

Thank your in advance提前感谢您

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

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

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM