简体   繁体   中英

Trying to create bundle with ArrayList<string> and pass it to another activity VIA Intent

I hope someone can help me with the question. I have looked all over and tried many suggestions as to how to get bundles from one activity to another. Most suggestions I have tried and they still do not work, I thought the following code would work but it doesn't. I believe I am getting null when I try to get the bundle in the new activity. Here is the code:

In my SyncActivity Class I have this:

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
                deviceList.add(device.getName());
                deviceList.add(device.getAddress());
                deviceList.add(device.getUuids().toString());
            }
        }

        Intent myIntent = new Intent(SyncActivity.this, BlueToothConnThread.class);
        Bundle myBundle = new Bundle();
        myBundle.putStringArrayList("DeviceList", deviceList);
        myIntent.putExtras(myBundle);
        startActivity(myIntent);

In my BlueToothConnThread Class I do this:

 public BlueToothConnThread() {

    Bundle dataBundle = getIntent().getExtras();    
    deviceList = dataBundle.getStringArrayList("DeviceList");

}

The error is thrown after I try to initialize dataBundle with the getIntent().getExtras(); Any help greatly appreciated.

Thanks,

Russell

Here is how you pass it.

Intent intent = new Intent(ABC.this, DEF.class);
Bundle bundle = new Bundle();
bundle.putSerializable("ArrayList", yourArrayList);
intent.putExtras(bundle);  

And here is how you get it.

Bundle bundle = data.getExtras();
ArrayList<Bluetooth> bluetoothArrayList= (ArrayList<Bluetooth>) bundle.getSerializable("ArrayList");

I hope it helps :)

You cannot receive Bundle in some arbitrary method. You can get the bundle in OnCreate method of the Activity. Then only it works.

 public BlueToothConnThread extends Activity {

    @Override
    public void onCreate(Bundle onSavedInstanceState) {
     //Some code

    Bundle dataBundle = getIntent().getExtras();    
    deviceList = dataBundle.getStringArrayList("DeviceList");
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM