我試圖從Bluetooth - Android Developers如何直接將數據添加到arrayAdapter?
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
// If there are paired devices
if (pairedDevices.size() > 0) {
// 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());
}
}
使用此代碼,但我不能將數據添加到myArrayAdapter
,因爲它放置在private void onCreate()
相加法拋出錯誤,有沒有這樣的適配器。
我需要直接將數據添加到一個ArrayAdapter,因爲它應該在我的活動列表視圖刷新時,發現了一些新的設備。
另外我可以使用myArrayAdapter.notifyDataSetChanged()
,但就像我說我的ArrayAdapter
置於onCreate
,所以它無法訪問它。
所以我的問題是如何在onCreate
之外放置arrayAdapter而沒有任何錯誤?
我的Java類代碼,如果neccesary:
public class DeviceList extends AppCompatActivity {
private final static int REQUEST_ENABLE_BT = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_device_list);
BluetoothAdapter BTAdapter = BluetoothAdapter.getDefaultAdapter();
if (BTAdapter != null) {
if (!BTAdapter.isEnabled()) {
Intent enableBT = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBT, REQUEST_ENABLE_BT);
}
if (BTAdapter.isDiscovering()) {
BTAdapter.cancelDiscovery();
}
BTAdapter.startDiscovery();
}
ArrayAdapter<String> myArrayAdapter;
ListView listView = (ListView) findViewById(R.id.inputELM);
myArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, myEntries);
listView.setAdapter(myArrayAdapter);
// Register the BroadcastReceiver
IntentFilter ifilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
this.registerReceiver(mReceiver, ifilter);
}
ArrayList<String> myEntries = new ArrayList<>();
// Create a BroadcastReceiver for ACTION_FOUND
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
String devs = device.getName() + "\n" + device.getAddress();
myEntries.add(devs);
}
}
};
}
你對字段/成員變量不瞭解麼? –