0

我有一个活动,我正在使用在类主体本身中声明的 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();

theBroadcastReceiver也在类主体中声明:

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 变为空?

4

1 回答 1

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 方法中。

于 2013-06-12T14:15:50.580 回答