2014-10-28 3 views
0

Я могу сканировать устройства Bluetooth из своего приложения и перечислить отсканированные устройства. Но я сталкиваюсь с проблемой при соединении устройств. Ниже кода, который я использовал в своем приложении,NullPointerException при подключении устройств 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-устройства, но всякий раз, когда я пытаюсь выполнить сопряжение, он дает исключение NullPointerException в строке 22. Какова будет причина исключения 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); 

} 

}

Благодаря

+0

Вы уверены, что 'mBluetoothdevice' не является нулевым? Можете ли вы дать нам стопку? :) – mithrop

+0

Возможно, у вас есть та же проблема? Здесь ссылка: http://stackoverflow.com/questions/26585037/receiving-broadcast-error-for-bluetooth-discovery-error-in-onrecieve-method/ – DMan

ответ

1

Скорее всего device равна нулю. Уверены ли вы, что mBluetoothdevice при загрузке страницы не найдено pairToBLE? Добавьте заявление Log, чтобы узнать, что это такое.

+0

Да, mBluetoothdevice имеет значение null. Как сделать это не имеет значения null – Shiv

+0

Вы не предоставили достаточный код. Покажите, что вы делаете, чтобы присвоить значение 'mBluetoothdevice'. – akodiakson

+0

Проверка pl отредактирована Вопрос – Shiv

Смежные вопросы