问一下本人在蓝牙ble调试的时候,搜索蓝牙设备的时候报这个错:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.mybleyyy/com.example.mybleyyy.ControlActivity}: java.lang.NullPointerException: Attempt to invoke virtual method “boolean android.bluetooth.BluetoothAdapter.startLeScan(android.bluetooth.BluetoothAdapter$LeScanCallback)” on a null object reference
是哪里出问题了?
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.mybleyyy/com.example.mybleyyy.ControlActivity}: java.lang.NullPointerException: Attempt to invoke virtual method “boolean android.bluetooth.BluetoothAdapter.startLeScan(android.bluetooth.BluetoothAdapter$LeScanCallback)” on a null object reference
是哪里出问题了?
private void scanLeDevice(final boolean enable) { if (enable) { // Stops scanning after a pre-defined scan period. mHandler.postDelayed(new Runnable() { @Override public void run() { mScanning = false; adapter.stopLeScan(mLeScanCallback); invalidateOptionsMenu(); } }, 10000); mScanning = true; adapter.startLeScan(mLeScanCallback); //mScanning = false; //adapter.stopLeScan(mLeScanCallback); //System.err.println("*************停止BLE扫描*************"); for(BluetoothDevice btd : bluetoothDevicesSet){ HashMap<String, String> mapName = new HashMap<String, String>(); mapName.put("ItemTitle", btd.getName()+"/address:"+btd.getAddress()); System.err.println("*************ItemTitle*************"+btd.getName()); mylist.add(mapName); bluetoothDevicesList.add(btd); simpleAdapter = new SimpleAdapter(getApplicationContext(), mylist, R.layout.bt_device_list, new String[] {"ItemTitle"}, new int[] {R.id.device_name}); //加载SimpleAdapter到ListView中 listview_newDevices.setAdapter(simpleAdapter); }} else { mScanning = false; adapter.stopLeScan(mLeScanCallback); } invalidateOptionsMenu(); }
private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() { @Override public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) { runOnUiThread(new Runnable() { @Override public void run() { System.err.println("onLeScan:"+device.getAddress()+"*******"+device.getName()+"*******"); Toast.makeText(ControlActivity.this, "onLeScan:"+device.getAddress()+"*******"+device.getName()+"*******", Toast.LENGTH_SHORT).show(); bluetoothDevicesSet.add(device); } }); } };
解决方案
30
你for循环应该写在mLeScanCallback 这个回调里面吧,写在外面的话蓝牙还没有搜索到设备,你就开始循环了,就空指针了。
5
不是不是你的adapter在执行这段代码前还没有初始化
5
adapter为null