简体   繁体   中英

How to use the same ArrayList in different activities (Android and Java)

I am working on a little app and needed a way of making it so when a button is pushed it opens up a random activity, and then doesn't open up that activity again.

I did this by making an ArrayList which is randomly sorted and has a number chosen from it. This number is then deleted. The number chosen is then used to open up one of the activities.

However, when I get to another activity I cannot use the same ArrayList from before (with all the same numbers in).

Is there a way to move the ArrayList from activity to activity?

Thanks in advance!

Here is my code for making the ArrayList and picking a number:

                int min = 1;
                int max = 3;
                ArrayList<Integer> list = new ArrayList<Integer>();
                for(int i = min; i <= max; i++) list.add(i);
                Collections.shuffle(list);

                Integer x = list.get(0);
                list.remove(0); 

You can pass it in your startActivity intent (intent.putExtra) or you can use a static variable in your application class:

How to declare global variables in Android?

For passing an ArrayList with an intent, this is a very useful post:

Pass arraylist of user defined objects to Intent android

Basically, if you use all primitives you can pass them without creating parcelable objects to put into it. You also do not have to create a parcelable object (because objects that do not extend or implement parcelable cannot successfully be passed in an intent even though you will not see any errors).

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