我想让我的蓝牙列表仅显示一台设备。我尝试过,我用开关盒做到了。但是我们使用break来关闭程序。 如果我使用if-else,则我的程序再次关闭。 这是我的原始代码:
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
Log.d(TAG, "onReceive: ACTION FOUND.");
// mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (action.equals(BluetoothDevice.ACTION_FOUND)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
mBTDevices.add(device);
Log.d(TAG, "onReceive: " + device.getName() + ": " + device.getAddress());
mDeviceListAdapter = new DeviceListAdapter(getActivity(), R.layout.device_adapter_view, mBTDevices);
lvData.setAdapter(mDeviceListAdapter);
}
这是开关盒:
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
Log.d(TAG, "onReceive: ACTION FOUND.");
// mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (action.equals(BluetoothDevice.ACTION_FOUND)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
switch (String.valueOf(device.getName())) {
case "MyDevice" :
mBTDevices.add(device);
Log.d(TAG, "onReceive: " + device.getName() + ": " + device.getAddress());
mDeviceListAdapter = new DeviceListAdapter(getActivity(), R.layout.device_adapter_view, mBTDevices);
lvData.setAdapter(mDeviceListAdapter);
break;
}
}
}
这是我的Logcat:
Process: com.example.duygu.mybluetoothdevicelist, PID: 11510
java.lang.RuntimeException: Error receiving broadcast Intent { act=android.bluetooth.device.action.FOUND flg=0x10 (has extras) } in com.example.duygu.mybluetoothdevicelist.BluetoothListFragment$1@33c56d3
at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:935)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5525)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:730)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:620)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.hashCode()' on a null object reference
at com.example.duygu.mybluetoothdevicelist.BluetoothListFragment$1.onReceive(BluetoothListFragment.java:108)
at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:925)