配对蓝牙设备时出现NullPointerException

时间:2014-10-28 13:39:45

标签: 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;

    }

我注册了Contextmenu。在此之前,我能够扫描并列出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);

}

}

谢谢

1 个答案:

答案 0 :(得分:1)

最有可能device为空。致电mBluetoothdevice时,您确定pairToBLE不为空吗?添加Log语句以查看它是什么。