
本文详解如何避免 NullPointerException,通过优化 RecyclerView Adapter 设计与事件回调机制,安全地将扫描到的蓝牙设备从 ScanActivity 传递至业务逻辑层,并支持后续连接操作。重点涵盖适配器单例初始化、线程安全更新、点击事件解耦及设备去重处理。
本文详解如何避免 `nullpointerexception`,通过优化 recyclerview adapter 设计与事件回调机制,安全地将扫描到的蓝牙设备从 `scanactivity` 传递至业务逻辑层,并支持后续连接操作。重点涵盖适配器单例初始化、线程安全更新、点击事件解耦及设备去重处理。
在 Android 蓝牙开发中,一个常见却极易引发崩溃的问题是:在 BroadcastReceiver 中频繁创建新 RecyclerView.Adapter 实例,并试图直接访问未初始化或已被回收的 BluetoothDevice 对象——这正是原始代码中 NullPointerException 的根本原因。问题核心不在于“如何传设备”,而在于“如何以线程安全、生命周期一致、职责清晰的方式组织数据流”。
✅ 正确的数据流向设计原则
Adapter 单次初始化,多次复用
❌ 错误:每次发现设备都新建Bluetooth_adapter(data, context)并调用setAdapter()
✅ 正确:onCreate()中仅初始化一次BluetoothScanListAdapter,并通过addDevice()方法动态更新数据集。-
UI 更新必须在主线程执行
BroadcastReceiver.onReceive()运行在 Binder 线程,不可直接操作RecyclerView或View。应使用Handler.post()或runOnUiThread()切换至主线程:handler.post(() -> scanListAdapter.addDevice(new BluetoothDeviceModel(name, address, logoRes)));
-
点击事件解耦:使用接口回调替代构造函数传参
不要尝试在ViewHolder中持有BluetoothDevice引用(易因列表复用失效),而是通过定义DeviceSelectListener接口,在点击时将完整的BluetoothDeviceModel安全回传:public interface DeviceSelectListener { void onDeviceSelected(BluetoothDeviceModel deviceModel); }
? 关键代码重构实践
Step 1:重构 ScanActivity —— 初始化监听器与 Adapter
// onCreate() 中一次性设置
final DeviceSelectListener deviceSelectListener = new DeviceSelectListener() {
@Override
public void onDeviceSelected(BluetoothDeviceModel deviceModel) {
// ✅ 安全获取已选设备信息
String address = deviceModel.getAddress();
String name = deviceModel.getName();
// ? 启动连接 Activity(示例)
Intent intent = new Intent(ScanActivity.this, ConnectActivity.class);
intent.putExtra("device_address", address);
intent.putExtra("device_name", name);
startActivity(intent);
// 或直接调用连接逻辑(需适配 Android 12+ 权限)
// connectToDevice(address);
}
};
scanListAdapter = new BluetoothScanListAdapter(deviceSelectListener);
recyclerViewSD.setAdapter(scanListAdapter);
Step 2:重构 BluetoothScanListAdapter —— 支持动态添加与安全点击
public class BluetoothScanListAdapter extends RecyclerView.Adapter<bluetoothviewholder> {
private final List<bluetoothdevicemodel> devices = new ArrayList();
private final DeviceSelectListener selectListener;
public BluetoothScanListAdapter(DeviceSelectListener selectListener) {
this.selectListener = selectListener;
}
// ✅ 线程安全添加设备(自动去重)
public void addDevice(BluetoothDeviceModel device) {
if (devices.stream().noneMatch(d -> d.getAddress().equals(device.getAddress()))) {
devices.add(device);
notifyItemInserted(devices.size() - 1); // 局部刷新,性能更优
}
}
@Override
public void onBindViewHolder(@NonNull BluetoothViewHolder holder, int position) {
BluetoothDeviceModel model = devices.get(position);
holder.deviceNamePD.setText(model.getName() != null ? model.getName() : model.getAddress());
holder.dropdownImgPD.setImageResource(model.getImageresouce());
holder.cardViewPD.setOnClickListener(v -> {
int pos = holder.getAbsoluteAdapterPosition(); // ✅ 使用绝对位置防复用错位
if (pos >= 0 && pos <h3>⚠️ 必须注意的陷阱与最佳实践</h3>
<ul>
<li>
<strong>权限适配(Android 12+)</strong>:<code>BLUETOOTH_SCAN</code>、<code>BLUETOOTH_CONNECT</code>、<code>ACCESS_FINE_LOCATION</code> 需动态申请,且 <code>onReceive()</code> 中不可直接调用 <code>requestPermissions()</code>(非 Activity 上下文)。应在 <code>onCreate()</code> 或用户触发扫描前统一申请。</li>
<li>
<strong>广播接收器生命周期</strong>:务必在 <code>onResume()</code> 注册、<code>onPause()</code> 及时注销,避免内存泄漏;<code>cancelDiscovery()</code> 应在 <code>onPause()</code> 和 <code>reload()</code> 中调用。</li>
<li>
<strong>设备地址唯一性</strong>:使用 <code>device.getAddress()</code> 做去重判断(而非名称),因名称可能为空或重复。</li>
<li>
<strong>连接前校验</strong>:传递 <code>address</code> 至目标 Activity 后,需再次通过 <code>BluetoothAdapter.getRemoteDevice(address)</code> 获取 <code>BluetoothDevice</code> 实例,并检查是否支持 <code>fetchUuidsWithSdp()</code> 或 <code>createBond()</code>。</li>
<li>
<strong>避免 <code>handler.postDelayed()</code> 误用</strong>:原始代码中每次发现设备都触发 <code>4s</code> 延迟隐藏进度条,会导致多次执行。应改为扫描结束统一处理(如监听 <code>BluetoothAdapter.ACTION_DISCOVERY_FINISHED</code>)。</li>
</ul>
<h3>✅ 总结:构建健壮蓝牙设备交互链路</h3>
<table>
<thead><tr>
<th>环节</th>
<th>关键动作</th>
<th>目的</th>
</tr></thead>
<tbody>
<tr>
<td><strong>扫描发现</strong></td>
<td>
<code>startDiscovery()</code> + <code>ACTION_FOUND</code> 广播</td>
<td>获取设备元数据</td>
</tr>
<tr>
<td><strong>UI 同步</strong></td>
<td>
<code>Handler.post()</code> → <code>adapter.addDevice()</code>
</td>
<td>线程安全更新列表</td>
</tr>
<tr>
<td><strong>用户选择</strong></td>
<td>
<code>ViewHolder</code> 点击 → <code>getAbsoluteAdapterPosition()</code> → 回调</td>
<td>避免复用导致的 <code>NullPointerException</code>
</td>
</tr>
<tr>
<td><strong>跨组件传递</strong></td>
<td>
<code>Intent.putExtra()</code> 传递 <code>address</code>/<code>name</code>
</td>
<td>解耦 UI 与连接逻辑</td>
</tr>
<tr>
<td><strong>后续连接</strong></td>
<td>在目标 Activity 中 <code>getRemoteDevice()</code> + 权限校验 + <code>createBond()</code>
</td>
<td>安全建立配对</td>
</tr>
</tbody>
</table>
<p>通过以上重构,你将获得一个可维护、无崩溃风险、符合 Android 架构规范的蓝牙设备扫描与连接流程。记住:<strong>设备不是“传过去”的对象,而是“被引用并安全操作”的资源</strong>——设计的核心永远是生命周期感知与线程边界控制。</p></bluetoothdevicemodel></bluetoothviewholder>











