ArrayAdapter NullPointerException in BroadcastReceiver onRec



我有一个活动,我使用的是在类体本身声明的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变为null?

你有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);

最新更新