我正在使用Java制作蓝牙应用程序。我创建了一个Devicelist活动来显示配对的所有设备和新发现的设备。当我从父活动打开此活动并单击某个设备时,MAC地址将从Devicelist发送到父活动,但是一旦我尝试从其中获取BluetoothDevice,我的应用程序崩溃(Logcat在下面)。
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
}
}
};
我从putExtra获取MAC地址。我甚至在textView上显示它以确保我得到正确的地址,但每次我尝试将蓝牙设备从中取出时,我的应用程序崩溃。
日志
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 :(得分: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();
}
}
}
}
};