2016-04-12 5 views
0

Я делаю приложение bluetooth с Java. Я создал активность Devicelist, чтобы показать все устройства в паре и вновь обнаруженные устройства. Когда я открываю это действие из родительского действия и нажимаю на устройство, MAC-адрес отправляется из Devicelist в родительскую активность, но как только я попытаюсь вытащить BluetoothDevice, мое приложение аварийно завершает работу (Logcat ниже).getRemoteDevice дает ошибку

DeviceList.java

public static String EXTRA_DEVICE_ADDRESS = "device_address"; 

private final BroadcastReceiver mReceiver = new BroadcastReceiver() { 
    @Override 
    public void onReceive(Context context, Intent intent) { 
     String action = intent.getAction(); 

     // When discovery finds a device 
     if (BluetoothDevice.ACTION_FOUND.equals(action)) { 
      // Get the BluetoothDevice object from the Intent 
      BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); 
      // If it's already paired, skip it, because it's been listed already 
      if (device.getBondState() != BluetoothDevice.BOND_BONDED) { 
       mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress()); 
      } 
     } 
    } 
} 

private AdapterView.OnItemClickListener mDeviceClickListener = new AdapterView.OnItemClickListener() { 
    public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) { 
     // Cancel discovery because it's costly and we're about to connect 
     mBtAdapter.cancelDiscovery(); 

     // Get the device MAC address, which is the last 17 chars in the View 
     String info = ((TextView) v).getText().toString(); 
     String address = info.substring(info.length() - 17); 

     // Create the result Intent and include the MAC address 
     Intent data = new Intent(); 
     data.putExtra(EXTRA_DEVICE_ADDRESS, address); 

     // Set result and finish(=close?) this Activity 
     setResult(RESULT_OK, data); 
     finish(); 
    } 
}; 

TribotActivity (мой родительский класс)

@Override 
protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
    if (requestCode == REQUEST_DEVICE_ADDRESS) {  // Check which request we're responding to. When doing more requests a switch case is probably a nicer way of doing this. 
     if (resultCode == RESULT_OK) {     // Make sure the request was successful 
      if (data.hasExtra("device_address")) { 
       Bundle bundleResult = data.getExtras(); // Store the Intent data(=device address) that we've received from the DeviceListActivity TODO Figure out why we can't simply use "String device = data.getStringExtra("device");" 
       String address = bundleResult.getString("EXTRA_DEVICE_ADDRESS"); 
       //String address = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS); 
       BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address); 

       //BluetoothConnect.connect(device); 

       textView = (TextView) findViewById(R.id.textView2); 
       textView.setText("Device address: " + address); 
      } else { 
       Toast.makeText(getApplicationContext(), "Failed to get MAC address", Toast.LENGTH_SHORT).show(); //TODO Remove this when we've successfully sent through the address 
      } 
     } else { 
      Toast.makeText(getApplicationContext(), "Failed to get MAC address", Toast.LENGTH_SHORT).show(); //TODO Remove this when we've successfully sent through the address 
     } 
    } 
}; 

я получить MAC-адрес из putExtra. Я даже показываю его на textView, чтобы убедиться, что получаю правильный адрес, но каждый раз, когда я пытаюсь вытащить BluetoothDevice, мое приложение падает.

Вход

04-04 12:12:50.638 10364-10364/com.hszuyd.noodle_.testing E/AndroidRuntime: FATAL EXCEPTION: main 
    Process: com.hszuyd.noodle_.testing, PID: 10364 
    Theme: themes:{} 
    java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { (has extras) }} to activity {com.hszuyd.noodle_.testing/com.hszuyd.noodle_.testing.TribotActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.bluetooth.BluetoothDevice android.bluetooth.BluetoothAdapter.getRemoteDevice(java.lang.String)' on a null object reference 
    at android.app.ActivityThread.deliverResults(ActivityThread.java:3733) 
    at android.app.ActivityThread.handleSendResult(ActivityThread.java:3776) 
    at android.app.ActivityThread.-wrap16(ActivityThread.java) 
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1412) 
    at android.os.Handler.dispatchMessage(Handler.java:102) 
    at android.os.Looper.loop(Looper.java:148) 
    at android.app.ActivityThread.main(ActivityThread.java:5461) 
    at java.lang.reflect.Method.invoke(Native Method) 
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
    at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:117) 
    Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.bluetooth.BluetoothDevice android.bluetooth.BluetoothAdapter.getRemoteDevice(java.lang.String)' on a null object reference 
    at com.hszuyd.noodle_.testing.TribotActivity.onActivityResult(TribotActivity.java:88) 
    at android.app.Activity.dispatchActivityResult(Activity.java:6456) 
    at android.app.ActivityThread.deliverResults(ActivityThread.java:3729) 
    at android.app.ActivityThread.handleSendResult(ActivityThread.java:3776) 
    at android.app.ActivityThread.-wrap16(ActivityThread.java) 
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1412) 
    at android.os.Handler.dispatchMessage(Handler.java:102) 
    at android.os.Looper.loop(Looper.java:148) 
    at android.app.ActivityThread.main(ActivityThread.java:5461) 
    at java.lang.reflect.Method.invoke(Native Method) 
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
    at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:117) 

Я надеюсь, что вы, ребята, можете мне помочь! Спасибо.

ответ

0

На первый взгляд: RuntimeException: пытаются обернуть редактирования кода TextView в этом:

synchronized (this) { 
     runOnUiThread(new Runnable() { 
      @Override 
      public void run() { 
       textView = (TextView) findViewById(R.id.textView2); 
       textView.setText("Device address: " + address); 
      } 
     }); 
    } 

NullPointerException: Я не уверен, что в вашем варианте, чтобы получить удаленное устройство. В моей стороне сервера кода это работает:

 serverSocket = bluetoothAdapter.listenUsingRfcommWithServiceRecord(SERVICE_NAME, java.util.UUID.fromString(UUID)); 
     clientSocket = serverSocket.accept(); 
     if (clientSocket != null) 
      clientDevice = clientSocket.getRemoteDevice(); //remember client 

А на стороне клиента:

private final BroadcastReceiver discoveryStartedReceiver = new BroadcastReceiver() { 
     @Override 
     public void onReceive(Context context, Intent intent) { 
      String action = intent.getAction(); 
      // When discovery finds a device 
      if (BluetoothDevice.ACTION_FOUND.equals(action)) { 
       // Get the BluetoothDevice object from the Intent 
       BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); 
       discoveredDevices.add(device); 
       // Add the name and address to an array adapter to show in a ListView 
       btDevicesAdapterList.add(device.getName() + "\n" + device.getAddress()); 

       //TODO 
       if ((device.getName().equals(ROBOT_SERVER_NAME))){ 
        if (clientState != CLIENT_CONNECTING) { 
         selectedServer = device; 
         Log.i(TAG, "SelectedServer: " + selectedServer.getName()); 
         bluetoothAdapter.cancelDiscovery(); 
         connectMethod(); 
        } 
       } 
      } 
     } 
    }; 
Смежные вопросы