我现在正在关注谷歌蓝牙教程并加入了ArrayAdapter。
基本上我想列出配对和找到的蓝牙设备。
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ArrayAdapter.add(java.lang.Object)' on a null object reference at eighttech.eu.obd2_8scan.fragments.FragmentBluetooth.onCreateView(FragmentBluetooth.java:44)
以下是代码:
public class FragmentBluetooth extends Fragment {
public FragmentBluetooth(){}
private ArrayAdapter<String> mArrayAdapter;
BluetoothAdapter mBluetoothAdapter;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_bluetooth, container, false);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter.isEnabled()) {
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
// If there are paired devices
if (pairedDevices.size() > 0) {
mArrayAdapter.add("Paired devices");
// Loop through paired devices
for (BluetoothDevice device : pairedDevices) {
// Add the name and address to an array adapter to show in a ListView
mArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
mArrayAdapter.add("Discovered devices");
// Register the BroadcastReceiver
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
getActivity().registerReceiver(mReceiver, filter); // Don't forget to unregister during onDestroy
mBluetoothAdapter.startDiscovery();
ListView listView = (ListView) rootView.findViewById(R.id.ListPairedDevices);
listView.setAdapter(mArrayAdapter);
}
}
return rootView;
}
final BroadcastReceiver mReceiver = new BroadcastReceiver() { // Create a BroadcastReceiver for ACTION_FOUND
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) { // When discovery finds a device
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// Add the name and address to an array adapter to show in a ListView
mArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
}
};
@Override
public void onResume() {
super.onResume();
IntentFilter intentFilter = new IntentFilter();
getActivity().registerReceiver(mReceiver, intentFilter);
}
@Override
public void onPause() {
super.onPause();
getActivity().unregisterReceiver(mReceiver);
}
}
我不知道如何解决这个问题,并没有为我的问题找到解决方案。
答案 0 :(得分:0)
在将项目添加到arrayadapter之前添加此项:
mArrayAdapter = new ArrayAdapter<String>();