我有一个活动,我使用在类体本身中声明的ArrayAdapter:
ArrayAdapter<String> btDevArrayAdapter = null;
在我的onCreate()函数中,我执行以下操作:
ListView btDevList = (ListView)findViewById(R.id.btList);
ArrayAdapter<String> btDevArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
btDevList.setAdapter(btDevArrayAdapter);
btDevArrayAdapter.add("test");
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
if (btDevArrayAdapter==null) {
Log.d("ARRAY ADAPTER ON CREATE"," I AM NULL");
} else {
Log.d("ARRAY ADAPTER"," I AM INITIALIZED "); //this always shows up
}
稍后,我注册了一个广播接收器
registerReceiver(mReceiver, filter);
启动蓝牙设备发现
btAdapter.startDiscovery();
BroadcastReceiver
也在类体中声明:
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
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);
// Add the name and address to an array adapter to show in a ListView
if (btDevArrayAdapter==null) {
Log.d("ARRAY ADAPTER"," I AM NULL"); // <-- NullPointerException
} else {
if (device == null)
btDevArrayAdapter.add("was null!");
else
btDevArrayAdapter.add(device.getAddress());
}
}
}
};
看着我的logcat,它总是这样:
01-01 02:34:02.200: D/ARRAY ADAPTER(1745): I AM INITIALIZED
01-01 02:34:05.393: D/ARRAY ADAPTER(1745): I AM NULL
什么可能导致ArrayAdapter变为空?
答案 0 :(得分:1)
你有NPE,因为你启动了一个只在onCreate方法中可见的适配器:
ArrayAdapter<String> btDevArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
将其更改为:
btDevArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
在你的onCreate-Method中。