java - 配对蓝牙设备时出现 NullPointerException

标签 java android bluetooth

我可以从我的应用程序扫描蓝牙设备并列出扫描的设备。但我在配对设备时遇到问题。下面的代码是我在我的应用程序中使用的,

 private void pairToBLE(BluetoothDevice device) {
        // TODO Auto-generated method stub      
        try {           

22.            Method method = device.getClass().getMethod("createBond", (Class[]) null);
               method.invoke(device, (Object[]) null);

        } catch (NoSuchMethodException e) {
          }

我在这里调用了上面的函数。

@Override
    public boolean onContextItemSelected(MenuItem item) {
        // TODO Auto-generated method stub      

        switch (item.getItemId()) {
        case R.id.menu_connect:   

            pairToBLE(mBluetoothdevice);        
            break;

    }

我注册了上下文菜单。在此之前,我能够扫描并列出 BT 设备,但每当我尝试配对时,它都会在第 22 行给出 NullPointerException。出现 NullpointerException 的原因是什么。完整代码在这里

public class AvailableDevices extends ListFragment {

    String TAG = "com.example.tracker.AvailableDevices";


    private LeDeviceListAdapter mLeDeviceListAdapter;




    private Handler mHandler;   
    private boolean mScanning;  
    Context context;

    public BluetoothDevice mBluetoothdevice;



    // Stops scanning after 10 seconds.
    private static final long SCAN_PERIOD = 10000;


    BLEService mBLEService;
    private String mDeviceAddrees;
    private String mDeviceName;






    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onActivityCreated(savedInstanceState);
        Log.i(TAG, "inside onActivityCreated");     

        context = AvailableDevices.this.getActivity();

        mLeDeviceListAdapter =  new LeDeviceListAdapter();  

        //System.out.println("value of adapter=="+mLeDeviceListAdapter.getCount());
        setListAdapter(mLeDeviceListAdapter);

        scanLeDevice(true);


        registerForContextMenu(getListView());




    }


     public class LeDeviceListAdapter extends BaseAdapter{

        private ArrayList<BluetoothDevice> mLeDevices;
        private LayoutInflater mInflator;
        Bundle savedInstanceState;   


        public LeDeviceListAdapter() {
            // TODO Auto-generated constructor stub
            super();
            Log.i(TAG, "inside LeDeviceListAdapter");
            mLeDevices = new ArrayList<BluetoothDevice>();
            mInflator = AvailableDevices.this.getLayoutInflater(null);          

        }   


        public void addDevices(BluetoothDevice device){

            if(!mLeDevices.contains(device)){
                mLeDevices.add(device);     

                System.out.println("device added++++++++++"+mLeDevices.add(device));
            }

        }

        public BluetoothDevice getDevice(int position){
            return mLeDevices.get(position);
        }

        public void clear(){
            mLeDevices.clear();
        }



        @Override
        public int getCount() {
            // TODO Auto-generated method stub

            int count =  mLeDevices.size();
            System.out.println("device counted++++++++++"+count);
            return count;

        }
        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub




            return mLeDevices.get(position);
        }

        @Override
        public long getItemId(int i) {
            // TODO Auto-generated method stub

            System.out.println("device getItemId++++++++++"+i);
            return i;
        }

        @Override
        public View getView(int position, View view, ViewGroup parent) {
            // TODO Auto-generated method stub
            ViewHolder viewHolder;

            Log.i(TAG, "inside getView===>");

            if(view == null){

                view = mInflator.inflate(R.layout.avldev_frag, null);


                viewHolder = new ViewHolder();
                viewHolder.deviceAdress = (TextView)view.findViewById(R.id.device_address);
                viewHolder.deviceName = (TextView)view.findViewById(R.id.device_name);
                view.setTag(viewHolder);


            }else{

                viewHolder = (ViewHolder)view.getTag();

                Log.i(TAG, "inside ViewHolder===>"+viewHolder);
            }

            BluetoothDevice device = mLeDevices.get(position);
            final String deviceName = device.getName();
            if (deviceName != null && deviceName.length() > 0){


                 Log.i(TAG, "inside if*****");

                viewHolder.deviceName.setText(deviceName);
                 viewHolder.deviceAdress.setText(device.getAddress());

                 Log.i(TAG, "bounded devices*****===>"+BluetoothDevice.BOND_BONDED);
            }else{

                viewHolder.deviceName.setText(R.string.unknown_device);


            }    


              Log.i(TAG, "device name my app*****===>"+deviceName);

              return view;
        }





    }

    static class ViewHolder{

        TextView deviceAdress;
        TextView deviceName;

    }

    // Device scan callback.
    private  BluetoothAdapter.LeScanCallback mLeScanCallback =
            new BluetoothAdapter.LeScanCallback() {

                @Override
                public void onLeScan(final BluetoothDevice device, int rssi,
                         byte[] scanRecord) {
                    // TODO Auto-generated method stub

                     getActivity().runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            // TODO Auto-generated method stub                          

                            mLeDeviceListAdapter.addDevices(device);
                            mLeDeviceListAdapter.notifyDataSetChanged();   



                        }
                    });             

                }     

    };   

    // Device scan callback.
    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;
                    MainActivity.mBluetoothAdapter.stopLeScan(mLeScanCallback);
                    //invalidateOptionsMenu();
                }
            }, SCAN_PERIOD);*/

            Log.d(TAG, "inside scanLeDevice function****");
            mScanning = true;

            System.out.println("value of mBluetoothAdapter+++++++++++++++=="
               +MainActivity.mBluetoothAdapter.getName().toString());
            MainActivity.mBluetoothAdapter.startLeScan(mLeScanCallback);
            Log.d(TAG, "after start****");
        } else {
            mScanning = false;
            MainActivity.mBluetoothAdapter.stopLeScan(mLeScanCallback);
        }
        //invalidateOptionsMenu();
    }




@Override
public void onCreateContextMenu(ContextMenu menu, View v,
        ContextMenuInfo menuInfo) {
    // TODO Auto-generated method stub
    super.onCreateContextMenu(menu, v, menuInfo);

    menu.add(Menu.NONE, R.id.menu_connect, Menu.NONE, "Connect");
    menu.add(Menu.NONE, R.id.menu_disconnect, Menu.NONE, "Disconnect");
}


@Override
public boolean onContextItemSelected(MenuItem item) {
    // TODO Auto-generated method stub



    switch (item.getItemId()) {
    case R.id.menu_connect: 


        Log.d(TAG,"INSIDE MENU");           
        ConnectDevices();

        if(mBluetoothdevice == null){

             Log.d(TAG, "inside mBluetoothdevice  null *****");


        }else{

             Log.d(TAG, "inside mBluetoothdevice not null *****");
            pairToBLE(mBluetoothdevice);

        }



        break;

    case R.id.menu_disconnect :



    default:
        break;
    }
    return super.onContextItemSelected(item);
}


private void ConnectDevices(){

    int position = 0;
    final BluetoothDevice device = mLeDeviceListAdapter.getDevice(position);
    mDeviceAddrees = device.getAddress();   

    MainActivity.mBLEService.connect(mDeviceAddrees);
}

private void pairToBLE(BluetoothDevice device) {
    // TODO Auto-generated method stub      

    try {

           Log.d(TAG, "inside pairToBLE");
           Method method = device.getClass().getMethod("createBond", (Class[]) null);
           method.invoke(device, (Object[]) null);
           Log.d(TAG, "inside pairToBLE after *****");
    } catch (NoSuchMethodException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IllegalArgumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

@Override
public void onDestroyView() {
    // TODO Auto-generated method stub           
       super.onDestroyView();          
       scanLeDevice(false);

}

}

谢谢

最佳答案

很可能device为空。当您调用pairToBLE时,您确定mBluetoothdevice不为空吗?添加一个 Log 语句来查看它是什么。

关于java - 配对蓝牙设备时出现 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26609861/

相关文章:

java - 使用 BeanUtils 忽略子类中的属性

java - android:如何更改按钮点击布局?

android - 如何在 Jacoco 报告生成中公开 "sourceDirectories"?

java - Java同步等待和通知方法

Android 应用程序检测其他 Activity

java - 在 EditText 中将字符串转换为 double

android - 蓝牙 a2dp 配置文件如何工作?

c - ANSI C 蓝牙 API 和教程 Linux

android - 在没有使用 nRF Connect 的解决方法的情况下,无法使用自定义应用程序连接到 BLE 设备

java - 是否有系统变量保存 Android 设备特定的低电量阈值?