简体   繁体   中英

pass arraylist from one activity to other

如何将ArrayList从一个活动传递到其他活动?

It depends on the type of arraylist

  • putIntegerArrayListExtra(String name, ArrayList<Integer> value)

  • putParcelableArrayListExtra(String name, ArrayList<? extends Parcelable> value)

  • putStringArrayListExtra(String name, ArrayList<String> value)

  • putCharSequenceArrayListExtra(String name, ArrayList<CharSequence> value)

Then you can read from you next activity by replacing put with get with key string as argument,eg

myIntent.getStringArrayListExtra("arrayPeople");

You can create one bundle in bundle put parceable array list provided by labeeb and set to intent here is the code for

Intent i = new Intent(this,name.class);
Bundle b = new Bundle();
b.putIntegerArrayListExtra(String name, ArrayList<Integer> value);
//b.putParcelableArrayListExtra(String name, ArrayList<? extends Parcelable> value);
//b.putStringArrayListExtra(String name, ArrayList<String> value);
i.putExtra(String name,b);
startActivity(i);

And get data into another activity like

//pseudo code
Bundle b = getIntent().getExtra().putParcelableArrayListExtra(String name);

In revoked Activity you should use

Bundle bundle = getIntent().getExtras();             
ArrayList<String> stringArray = bundle.getStringArrayList(ParentActivity.STRING_LIST);

where ParentActivity.STRING_LIST is your key constant for the list.

According to me, create static class and put your array-list in it while you traverse from one activity to the other.

When you reach in another activity, access the value that you stored in the static class.

UPDATE
I've learned with time that it's a horrible practice. When the objects are wiped/recreated the Static values might be lost. and then we put a lot of data in memory too. Using anything like Parcelable is a good practice

When you create intent. you can set data by

intent.putExtra("keyName", "somevalue");

when intent B start you can get data by

Bundle extras = getIntent().getExtras();
if(extras !=null)
{
   String value = extras.getString("keyName");
}

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